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

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: "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 ListWorkOrderPage = () => {
  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(1);
  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);
  const [isLoading, setIsLoading] = React.useState(false);
  const [loader2, setLoader2] = React.useState(false);
  // Check if pageSize exists in local storage
  const pageSizeFromLocalStorage = localStorage.getItem("workOrderPageSize");
  const [searchFilter, setSearchFilter] = React.useState("");
  const location = useLocation();
  // 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,
    setValue,
    reset,
    formState: { errors },
  } = useForm({
    resolver: yupResolver(schema),
  });

  React.useEffect(() => {
    if (localStorage.getItem("workOrderTab") == "completed") {
      setCompletedActive(true);
      setPendingActive(false);
    } else {
      setCompletedActive(false);
      setPendingActive(true);
    }
  }, [location.pathname]);
  React.useEffect(() => {
    setSearchFilter(localStorage.getItem("workOrderSearchFilter") || "");
    const clearSearchFilter = () => {
      localStorage.removeItem("workOrderSearchFilter");
      setSearchFilter("");
    };

    // Set up beforeunload event listener
    const handleBeforeUnload = () => {
      clearSearchFilter();
    };

    window.addEventListener("beforeunload", handleBeforeUnload);

    return () => {
      window.removeEventListener("beforeunload", handleBeforeUnload);
    };
  }, [location.pathname]);

  // New useEffect to handle location changes
  React.useEffect(() => {
    if (!location.pathname.includes("work-order")) {
      localStorage.removeItem("workOrderSearchFilter");
      setSearchFilter("");
    }

    return () => {
      console.log("dhhdhhd");
      console.log(location.pathname);
      if (!location.pathname.includes("work-order")) {
        localStorage.removeItem("workOrderSearchFilter");
        localStorage.removeItem("workOrderTab");
        setSearchFilter("");
      }
    };
  }, [location.pathname]);

  React.useEffect(() => {
    if (localStorage.getItem("workOrderSearchFilter")) {
      if (pendingActive) {
        (async function () {
          await getData(1, pageSizeFromLocalStorage, {
            status: "pending",
            employee_name:
              localStorage.getItem("workOrderSearchFilter") || null,
          });
        })();
      } else if (completedActive) {
        (async function () {
          await getData(1, pageSizeFromLocalStorage, {
            status: "completed",
            employee_name:
              localStorage.getItem("workOrderSearchFilter") || null,
          });
        })();
      }
    }
  }, [localStorage.getItem("workOrderSearchFilter")]);

  const handleFilterByStatus = (status) => {
    if (status === "pending") {
      // setFilterTableData(filteredData);
      setPendingActive(true);
      localStorage.setItem("workOrderTab", "pending");
      setCompletedActive(false);
    } else if (status === "completed") {
      // setFilterTableData(filteredData);
      setCompletedActive(true);
      localStorage.setItem("workOrderTab", "completed");
      setPendingActive(false);
    }
  };

  function updatePageSize(limit) {
    (async function () {
      setLoader2(true);
      setPageSize(limit);
      await getData(1, limit);
      setLoader2(false);
      document.getElementById("mainContainer").scrollTo({
        top: 0,
        behavior: "smooth",
      });
    })();
    localStorage.setItem("workOrderPageSize", limit);
  }

  const callDataAgain = (page) => {
    (async function () {
      setLoader2(true);
      await getData(
        page,
        pageSizeFromLocalStorage ? Number(pageSizeFromLocalStorage) : pageSize
      );
      setLoader2(false);
      document.getElementById("mainContainer").scrollTo({
        top: 0,
        behavior: "smooth",
      });
    })();
  };

  function previousPage() {
    (async function () {
      setLoader2(true);
      await getData(
        currentPage - 1,
        pageSizeFromLocalStorage ? Number(pageSizeFromLocalStorage) : pageSize
      );
      setLoader2(false);
      document.getElementById("mainContainer").scrollTo({
        top: 0,
        behavior: "smooth",
      });
    })();
  }

  function nextPage() {
    (async function () {
      setLoader2(true);
      await getData(
        currentPage + 1,
        pageSizeFromLocalStorage
          ? Number(pageSizeFromLocalStorage)
          : pageSize || pageSize
      );
      setLoader2(false);
      document.getElementById("mainContainer").scrollTo({
        top: 0,
        behavior: "smooth",
      });
    })();
  }

  console.log(filterTableData, "filter");
  console.log(currentPage, "jdjhd");
  async function getData(
    pageNum,
    limitNum,
    filter = completedActive
      ? removeKeysWhenValueIsNull({
          status: "completed",
          employee_name: localStorage.getItem("workOrderSearchFilter"),
        })
      : removeKeysWhenValueIsNull({
          status: "pending",
          employee_name: localStorage.getItem("workOrderSearchFilter"),
        })
  ) {
    setIsLoading(true);
    try {
      console.log(pageNum, "268");
      const result = await getAllWorkOrderAPI(pageNum, limitNum || 10, 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);

      setIsLoading(false);
    } catch (error) {
      setIsLoading(false);
      tokenExpireError(dispatch, error.message);
    }
  }

  const onSubmit = (_data) => {
    let employee_name = getNonNullValue(_data.employee_name);
    let filter = {
      employee_name: employee_name,
      status: completedActive ? "completed" : "pending",
    };
    console.log(employee_name);
    setSearchFilter(employee_name);
    localStorage.setItem("workOrderSearchFilter", employee_name);
    getData(1, pageSize, removeKeysWhenValueIsNull(filter));
  };

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

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

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

  React.useEffect(() => {
    console.log(localStorage.getItem("workOrderSearchFilter"));
    if (pendingActive) {
      (async function () {
        await getData(1, pageSizeFromLocalStorage, {
          status: "pending",
          employee_name: localStorage.getItem("workOrderSearchFilter"),
        });
      })();
    } else if (completedActive) {
      (async function () {
        await getData(1, pageSizeFromLocalStorage, {
          status: "completed",
          employee_name: localStorage.getItem("workOrderSearchFilter"),
        });
      })();
    }
  }, [completedActive, pendingActive]);

  console.log(location.pathname);
  console.log(pageSize, "nsnns");

  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 - Just Employee Name */}
          <form onSubmit={handleSubmit(onSubmit)} className="mb-8">
            <div className="flex items-center gap-3">
              <input
                type="text"
                placeholder="Employee Name"
                defaultValue={searchFilter}
                {...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:font-normal  placeholder:text-bodydark 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 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}
                  </th>
                ))}
              </tr>
            </thead>
            {!isLoading && currentTableData.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 (cell.accessor === "create_at") {
                        return (
                          <td
                            key={index}
                            className="whitespace-nowrap px-6 py-4"
                          >
                            {moment(row[cell.accessor]).format("MM/DD/YYYY")}
                          </td>
                        );
                      }
                      if (cell.accessor === "writer_id") {
                        return (
                          <td
                            key={index}
                            className="whitespace-nowrap px-6 py-4"
                          >
                            {row.writer ? row.writer.name : "N/A"}
                          </td>
                        );
                      }
                      if (cell.accessor === "artist_id") {
                        return (
                          <td
                            key={index}
                            className="whitespace-nowrap px-6 py-4"
                          >
                            {row.artist ? row.artist.name : "N/A"}
                          </td>
                        );
                      }
                      if (cell.accessor === "engineer_id") {
                        return (
                          <td
                            key={index}
                            className="whitespace-nowrap px-6 py-4"
                          >
                            {row.engineer ? row.engineer.name : "N/A"}
                          </td>
                        );
                      }
                      if (cell.accessor === "status") {
                        let artistRowId = row.artist
                          ? Number(row.artist.id)
                          : null;
                        let engineerRowId = row.engineer
                          ? Number(row.engineer.id)
                          : null;
                        if (
                          artistRowId === engineerRowId &&
                          row.writer_submit_status === 1 &&
                          Number(row.status) !== 5
                        ) {
                          return (
                            <td
                              key={index}
                              className="whitespace-nowrap px-6 py-4"
                            >
                              Artist/Engineer
                            </td>
                          );
                        }
                        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-6 py-4"
                              >
                                Writer/Artist
                              </td>
                            );
                          } else if (row.status === 3) {
                            return (
                              <td
                                key={index}
                                className="whitespace-nowrap px-6 py-4"
                              >
                                Engineer
                              </td>
                            );
                          } else if (row.status === 5) {
                            return (
                              <td
                                key={index}
                                className="whitespace-nowrap px-6 py-4"
                              >
                                Completed
                              </td>
                            );
                          }
                        }
                        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-6 py-4"
                              >
                                Wri/Art/Eng
                              </td>
                            );
                          } else if (row.status === 5) {
                            return (
                              <td
                                key={index}
                                className="whitespace-nowrap px-6 py-4"
                              >
                                Completed
                              </td>
                            );
                          }
                        }
                      }
                      if (cell.mappingExist) {
                        return (
                          <td
                            key={index}
                            className="whitespace-nowrap px-6 py-4"
                          >
                            {cell.mappings[row[cell.accessor]]}
                          </td>
                        );
                      }
                      return (
                        <td
                          key={index}
                          className="whitespace-nowrap px-6 py-4 text-white"
                        >
                          {row[cell.accessor]}
                        </td>
                      );
                    })}
                  </tr>
                ))}
              </tbody>
            ) : isLoading && currentTableData.length === 0 ? (
              <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>
                <tr></tr>
                <tr></tr>
                <tr></tr>
                <tr></tr>
                <tr></tr>
              </tbody>
            ) : !isLoading && currentTableData.length === 0 ? (
              <tbody>
                <tr></tr>
                <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>
            ) : (
              isLoading && (
                <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>
                  <tr></tr>
                  <tr></tr>
                  <tr></tr>
                  <tr></tr>
                  <tr></tr>
                </tbody>
              )
            )}
          </table>

          {/* Pagination */}
          {filterTableData.length > 0 && !isLoading && (
            <div className="w-full px-4 py-10 md:px-6 2xl:px-9">
              <PaginationBar
                currentPage={currentPage}
                pageCount={pageCount}
                pageSize={pageSize}
                canPreviousPage={canPreviousPage}
                canNextPage={canNextPage}
                updatePageSize={updatePageSize}
                previousPage={previousPage}
                nextPage={nextPage}
                dataTotal={dataTotal}
                setCurrentPage={setPage}
                callDataAgain={callDataAgain}
              />
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

export default ListWorkOrderPage;
