import React from "react";
import { AuthContext, tokenExpireError } from "../authContext";
import { useForm } from "react-hook-form";
import { useNavigate } from "react-router-dom";
import { yupResolver } from "@hookform/resolvers/yup";
import * as yup from "yup";
import moment from "moment";
import { GlobalContext } from "Src/globalContext";
import { getNonNullValue, removeKeysWhenValueIsNull } from "Utils/utils";
import PaginationBar from "Components/PaginationBar";
import AddButton from "Components/AddButton";
import { getAllWorkOrderAPI } from "Src/services/workOrderService";
import Spinner from "Components/Spinner";
import { ClipLoader } from "react-spinners";

const columns = [
  {
    header: "Date",
    accessor: "create_at",
    isSorted: false,
    isSortedDesc: false,
    mappingExist: false,
    mappings: {},
  },
  {
    header: "Id",
    accessor: "workorder_code",
    isSorted: false,
    isSortedDesc: false,
    mappingExist: false,
    mappings: {},
  },
  {
    header: "Producer",
    accessor: "member_name",
    isSorted: false,
    isSortedDesc: false,
    mappingExist: false,
    mappings: {},
  },
  {
    header: "Writer",
    accessor: "writer_id",
    isSorted: false,
    isSortedDesc: false,
    mappingExist: false,
    mappings: {},
  },
  {
    header: "Artist",
    accessor: "artist_id",
    isSorted: false,
    isSortedDesc: false,
    mappingExist: false,
    mappings: {},
  },
  {
    header: "Engineer",
    accessor: "engineer_id",
    isSorted: false,
    isSortedDesc: false,
    mappingExist: false,
    mappings: {},
  },
  {
    header: "Status",
    accessor: "status",
    isSorted: false,
    isSortedDesc: true,
    mappingExist: true,
    mappings: {
      1: "Writer",
      2: "Artist",
      3: "Engineer",
      4: "Rejected",
      5: "Completed",
      6: "Inactive",
    },
  },
];

const AdminListWorkOrderPage = () => {
  const { dispatch, state: authState } = React.useContext(AuthContext);
  const { dispatch: globalDispatch } = React.useContext(GlobalContext);

  const [currentTableData, setCurrentTableData] = React.useState([]);
  const [filterTableData, setFilterTableData] = React.useState([]);
  // const [pageSize, setPageSize] = React.useState(10);
  const [pageCount, setPageCount] = React.useState(0);
  const [dataTotal, setDataTotal] = React.useState(0);
  const [currentPage, setPage] = React.useState(0);
  const [canPreviousPage, setCanPreviousPage] = React.useState(false);
  const [canNextPage, setCanNextPage] = React.useState(false);
  const [loading, setLoading] = React.useState(false);

  const [pendingActive, setPendingActive] = React.useState(true);
  const [completedActive, setCompletedActive] = React.useState(false);

  // Check if pageSize exists in local storage
  const pageSizeFromLocalStorage = localStorage.getItem("workOrderPageSize");

  // Use a state variable to manage the pageSize
  const [pageSize, setPageSize] = React.useState(
    pageSizeFromLocalStorage ? Number(pageSizeFromLocalStorage) : 10 // Default pageSize
  );

  const navigate = useNavigate();

  const schema = yup.object({
    writer_id: yup.string(),
    artist_id: yup.string(),
    engineer_id: yup.string(),
  });
  const {
    register,
    handleSubmit,
    setError,
    reset,
    formState: { errors },
  } = useForm({
    resolver: yupResolver(schema),
  });

  const handleFilterByStatus = (status) => {
    if (status === "pending") {
      let filteredData = currentTableData.filter((item) => {
        return item.status === 1 || item.status === 2 || item.status === 3;
      });
      setFilterTableData(filteredData);
      setPendingActive(true);
      setCompletedActive(false);
    } else if (status === "completed") {
      let filteredData = currentTableData.filter((item) => {
        return item.status === 5;
      });
      setFilterTableData(filteredData);
      setCompletedActive(true);
      setPendingActive(false);
    }
  };

  function updatePageSize(limit) {
    (async function () {
      setPageSize(limit);
      await getData(1, limit);
    })();
    localStorage.setItem("workOrderPageSize", limit);
  }

  function previousPage() {
    (async function () {
      // await getData(currentPage - 1 > 0 ? currentPage - 1 : 0, pageSize);
      await getData(
        currentPage - 1,
        pageSizeFromLocalStorage ? Number(pageSizeFromLocalStorage) : pageSize
      );
    })();
  }

  function callDataAgain(page) {
    (async function () {
      // await getData(currentPage - 1 > 0 ? currentPage - 1 : 0, pageSize);
      await getData(
        page,
        pageSizeFromLocalStorage ? Number(pageSizeFromLocalStorage) : pageSize
      );
    })();
  }
  function nextPage() {
    (async function () {
      // await getData(
      //   currentPage + 1 <= pageCount ? currentPage + 1 : 0,
      //   pageSize
      // );
      await getData(
        currentPage + 1,
        pageSizeFromLocalStorage ? Number(pageSizeFromLocalStorage) : pageSize
      );
    })();
  }

  async function getData(pageNum, limitNum, filter) {
    try {
      const result = await getAllWorkOrderAPI(pageNum, limitNum, filter);
      const { list, total, limit, num_pages, page } = result;
      setCurrentTableData(list);

      if (pendingActive) {
        let filteredData = list.filter((item) => {
          return item.status === 1 || item.status === 2 || item.status === 3;
        });
        setFilterTableData(filteredData);
      } else if (completedActive) {
        let filteredData = list.filter((item) => {
          return item.status === 5;
        });
        setFilterTableData(filteredData);
      } else {
        setFilterTableData(list);
      }

      setPageSize(limit);
      setPageCount(num_pages);
      setPage(page);
      setDataTotal(total);
      setCanPreviousPage(page > 1);
      setCanNextPage(page + 1 <= num_pages);
      setLoading(false);
    } catch (error) {
      setLoading(false);
      tokenExpireError(dispatch, error.message);
    }
  }

  const onSubmit = (_data) => {
    let employee_name = getNonNullValue(_data.employee_name);
    let filter = {
      employee_name: employee_name,
    };
    getData(1, pageSize, removeKeysWhenValueIsNull(filter));
  };

  const resetForm = async () => {
    reset();
    localStorage.setItem("workOrderPageSize", 10);
    setPageSize(10);
    await getData(1, pageSize);
  };

  React.useEffect(() => {
    globalDispatch({
      type: "SETPATH",
      payload: {
        path: "work-orders",
      },
    });

    // (async function () {
    //   await getData(1, pageSize);
    // })();

    if (!pageSizeFromLocalStorage) {
      // call the API to get the data
      (async function () {
        setLoading(true);
        await getData(1, pageSize);
      })();
    } else {
      // call the API to get the data
      (async function () {
        setLoading(true);
        await getData(1, pageSizeFromLocalStorage);
      })();
    }
  }, []);

  return (
    <div
      className="max-w-screen h-full p-4 md:p-4 lg:p-6 xl:p-8"
      id="mainContainer"
    >
      <div className="shadow-default rounded border border-strokedark bg-boxdark">
        {/* Header Section */}
        <div className="sm:px-6.5 border-b border-strokedark px-4 py-4 dark:border-strokedark">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-4">
              <h4 className="text-2xl font-semibold text-white dark:text-white">
                Work Orders
              </h4>
              <div className="flex items-center gap-2">
                <button
                  className={`rounded-md px-3 py-1 text-sm font-medium ${
                    pendingActive
                      ? "bg-primary text-white"
                      : "text-white hover:bg-meta-4"
                  }`}
                  onClick={() => handleFilterByStatus("pending")}
                >
                  Pending
                </button>
                <button
                  className={`rounded-md px-3 py-1 text-sm font-medium ${
                    completedActive
                      ? "bg-primary text-white"
                      : "text-white hover:bg-meta-4"
                  }`}
                  onClick={() => handleFilterByStatus("completed")}
                >
                  Completed
                </button>
              </div>
            </div>
            <AddButton link={`/${authState.role}/add-work-order`} />
          </div>
        </div>

        {/* Table Content */}
        <div className="p-4 md:p-6 2xl:p-10">
          {/* Search Form */}
          <form onSubmit={handleSubmit(onSubmit)} className="mb-8">
            <div className="flex items-center gap-3">
              <input
                type="text"
                placeholder="Employee Name"
                {...register("employee_name")}
                className="h-[36px] w-64 rounded border-[1.5px] border-form-strokedark bg-form-input px-3 py-2 text-sm outline-none transition placeholder:font-normal placeholder:text-bodydark focus:border-primary active:border-primary disabled:cursor-default disabled:bg-whiter dark:border-form-strokedark dark:bg-form-input dark:focus:border-primary"
              />
            </div>
            <div className="mt-3 flex items-center gap-2">
              <button
                type="submit"
                className="inline-flex h-[36px] items-center justify-center rounded-md bg-primary px-4 py-2 text-sm font-medium text-white hover:bg-opacity-90"
              >
                Search
              </button>
              <button
                onClick={resetForm}
                type="button"
                className="inline-flex h-[36px] items-center justify-center rounded-md border border-strokedark bg-danger px-4 py-2 text-sm font-medium text-white hover:bg-opacity-90"
              >
                Reset
              </button>
            </div>
          </form>

          {/* Table */}
          <table className="min-h-[120px] w-full table-auto">
            <thead className="bg-meta-4">
              <tr>
                {columns.map((column, i) => (
                  <th
                    key={i}
                    className="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-bodydark1"
                  >
                    {column.header}
                    {column.isSorted && (
                      <span>{column.isSortedDesc ? " ▼" : " ▲"}</span>
                    )}
                  </th>
                ))}
              </tr>
            </thead>

            {loading && (
              <tbody>
                <tr>
                  <td colSpan={columns.length} className="text-center">
                    <span className="trans relative m-4 animate-pulse whitespace-nowrap p-4 pb-8 text-xl font-semibold text-white ease-out">
                      <ClipLoader color="#fff" size={20} className="mr-3" />{" "}
                      Loading Workorders...
                    </span>
                  </td>
                </tr>
              </tbody>
            )}

            {!loading && filterTableData && filterTableData.length > 0 && (
              <tbody className="cursor-pointer">
                {filterTableData.map((row, i) => (
                  <tr
                    key={i}
                    // onClick={() =>
                    //   navigate(`/${authState.role}/edit-work-order/${row.id}`, {
                    //     state: row,
                    //   })
                    // }
                    className="border-b border-strokedark text-bodydark1 hover:bg-primary/5 dark:border-strokedark"
                  >
                    {columns.map((cell, index) => {
                      if (
                        row.auto_approve === 1 &&
                        row.writer_id === row.artist_id &&
                        row.writer_id === row.engineer_id
                      ) {
                        if (row.status === 1) {
                          return (
                            <td
                              key={index}
                              className="whitespace-nowrap px-4 py-4"
                            >
                              Wri/Art/Eng
                            </td>
                          );
                        } else if (row.status === 5) {
                          return (
                            <td
                              key={index}
                              className="whitespace-nowrap px-4 py-4"
                            >
                              Completed
                            </td>
                          );
                        }
                      }
                      if (cell.mappingExist) {
                        return (
                          <td
                            key={index}
                            className="whitespace-nowrap px-4 py-4"
                          >
                            {cell.mappings[row[cell.accessor]]}
                          </td>
                        );
                      }
                      if (cell.accessor === "member_name") {
                        return (
                          <td
                            key={index}
                            className="whitespace-nowrap px-4 py-4"
                          >
                            {row.user_name}
                          </td>
                        );
                      }
                      return (
                        <td
                          key={index}
                          className="whitespace-nowrap px-4 py-4 text-white"
                        >
                          {row[cell.accessor]}
                        </td>
                      );
                    })}
                  </tr>
                ))}
              </tbody>
            )}

            {!loading && (!filterTableData || filterTableData.length === 0) && (
              <tbody>
                <tr>
                  <td colSpan={columns.length} className="text-center">
                    <span className="relative top-[10px] m-4 p-4 font-semibold text-white">
                      No data found
                    </span>
                  </td>
                </tr>
              </tbody>
            )}
          </table>

          {/* Pagination */}
          {filterTableData && filterTableData.length > 0 && !loading && (
            <div className="mt-4">
              <PaginationBar
                dataTotal={dataTotal}
                currentPage={currentPage}
                pageCount={pageCount}
                pageSize={pageSize}
                canPreviousPage={canPreviousPage}
                canNextPage={canNextPage}
                updatePageSize={updatePageSize}
                previousPage={previousPage}
                nextPage={nextPage}
                callDataAgain={callDataAgain}
                setCurrentPage={setPage}
              />
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

export default AdminListWorkOrderPage;
