import { yupResolver } from "@hookform/resolvers/yup";
import React from "react";
import { useForm } from "react-hook-form";
import { useNavigate } from "react-router-dom";
import { ClipLoader } from "react-spinners";
import { retrieveAllMixSeasonsAPI } from "Src/services/mixSeasonService";
import * as yup from "yup";
import { AuthContext, tokenExpireError } from "../authContext";
import AddButton from "../components/AddButton";
import PaginationBar from "../components/PaginationBar";
import { GlobalContext } from "../globalContext";
import {
  getNonNullValue,
  removeKeysWhenValueIsNull,
  sortSeasonAsc,
} from "../utils/utils";
import CustomSelect2 from "../components/CustomSelect2";

const columns = [
  {
    header: "Season",
    accessor: "name",
    isSorted: false,
    isSortedDesc: false,
    mappingExist: false,
    mappings: {},
  },
  {
    header: "Status",
    accessor: "status",
    isSorted: false,
    isSortedDesc: false,
    mappingExist: true,
    mappings: {
      1: "Active",
      0: "Inactive",
    },
  },
];

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

  const [showAction, setShowAction] = React.useState(false);
  const [currentTableData, setCurrentTableData] = 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 [loader2, setLoader2] = React.useState(false);
  const [isLoading, setIsLoading] = React.useState(false);

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

  // 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({
    name: yup.string(),
    status: yup.string(),
  });

  const {
    register,
    handleSubmit,
    setError,
    reset,
    formState: { errors },
  } = useForm({
    resolver: yupResolver(schema),
  });

  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("mixSeasonPageSize", limit);
  }

  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
      );
      setLoader2(false);
      document.getElementById("mainContainer").scrollTo({
        top: 0,
        behavior: "smooth",
      });
    })();
  }

  async function getData(pageNum, limitNum, filter) {
    currentTableData.length <= 0 ? setIsLoading(true) : setLoader2(true);
    try {
      const result = await retrieveAllMixSeasonsAPI(pageNum, limitNum, filter);
      const { list, total, limit, num_pages, page } = result;
      setCurrentTableData(sortSeasonAsc(list));
      setPageSize(limit);
      setPageCount(num_pages);
      setPage(page);
      setDataTotal(total);
      setCanPreviousPage(page > 1);
      setCanNextPage(page + 1 <= num_pages);

      currentTableData.length <= 0 ? setIsLoading(false) : setLoader2(false);
    } catch (error) {
      currentTableData.length <= 0 ? setIsLoading(false) : setLoader2(false);
      tokenExpireError(dispatch, error.message);
    }
  }

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

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

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

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

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

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

  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="flex items-center justify-between border-b border-strokedark px-4 md:px-6 2xl:px-9">
          <h4 className="my-3 text-2xl font-semibold text-white dark:text-white">
            Mix Seasons
          </h4>
          <AddButton link={`/${authState.role}/add-mix-season`} />
        </div>

        {/* Search/Filter Section */}
        <div className="mb-4 border-b border-strokedark px-4 py-4 sm:px-6 2xl:px-9 dark:border-strokedark">
          <div className="">
            <form className="">
              <div className="flex items-center gap-3">
                {/* Season Input */}
                <div className="flex flex-col">
                  <label className="mb-1.5 text-sm font-medium text-white">
                    Season
                  </label>
                  <input
                    type="text"
                    placeholder="season"
                    {...register("name")}
                    className="h-[36px] w-64 rounded border-[1.5px] border-form-strokedark bg-form-input px-3 py-2 text-sm capitalize 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>

                {/* Status Select */}
                <div className="flex flex-col">
                  <label className="mb-1.5 text-sm font-medium text-white">
                    Status
                  </label>
                  <CustomSelect2
                    register={register}
                    name="status"
                    label="Select Status"
                    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"
                  >
                    <option value="">Select Status</option>
                    <option value="1">Active</option>
                    <option value="0">Inactive</option>
                  </CustomSelect2>
                </div>
              </div>

              {/* Action Buttons */}
              <div className="mt-3 flex items-center gap-2">
                <button
                  type="submit"
                  onClick={handleSubmit(onSubmit)}
                  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>
          </div>
        </div>

        {/* Table Section */}
        <div>
          <div className="custom-overflow min-h-[150px] overflow-x-auto">
            <table className="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-white ${
                        i === 0 ? "xl:pl-6 2xl:pl-9" : ""
                      }`}
                    >
                      {column.header}
                      {column.isSorted && (
                        <span>{column.isSortedDesc ? " ▼" : " ▲"}</span>
                      )}
                    </th>
                  ))}
                </tr>
              </thead>

              {!isLoading && currentTableData.length > 0 ? (
                <tbody className="cursor-pointer text-white">
                  {currentTableData.map((row, i) => (
                    <tr
                      key={i}
                      onClick={() =>
                        navigate(`/${authState.role}/view-mix-season/${row.id}`)
                      }
                      className="border-b border-strokedark hover:bg-primary/5"
                    >
                      {columns.map((cell, index) => (
                        <td
                          key={index}
                          className={`whitespace-nowrap px-4 py-4 ${
                            index === 0 ? "xl:pl-6 2xl:pl-9" : ""
                          }`}
                        >
                          {cell.mappingExist
                            ? cell.mappings[row[cell.accessor]]
                            : row[cell.accessor]}
                        </td>
                      ))}
                    </tr>
                  ))}
                </tbody>
              ) : isLoading && currentTableData.length === 0 ? (
                <tbody>
                  <tr>
                    <td colSpan={columns.length} className="text-center">
                      <span className="trans relative top-[30px] 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 Mix Seasons...
                      </span>
                    </td>
                  </tr>
                </tbody>
              ) : !isLoading && currentTableData.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>
              ) : null}
            </table>
          </div>
        </div>

        {/* Pagination */}
        {currentTableData.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>
  );
};

export default ListMixSeasonPage;
