import { yupResolver } from "@hookform/resolvers/yup";
import React from "react";
import { useForm } from "react-hook-form";
import { useNavigate } from "react-router-dom";
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 FormMultiSelect from "Components/FormMultiSelect";
import { ClipLoader } from "react-spinners";
import {
  getAllMembersForManager,
  retrieveAllForMixSeasonForManager,
} from "Src/services/managerServices";
import CustomSelect2 from "Components/CustomSelect2";

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

const ManagerListMixSeasonPage = () => {
  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 [loading, setLoading] = React.useState(false);

  const [producersForSelect, setProducersForSelect] = React.useState([]);
  const [selectedProducers, setSelectedProducers] = React.useState([]);
  const [managerMember, setManagerMember] = React.useState([]);

  // 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
  );

  // Add producer initialization state
  const [producersInitialized, setProducersInitialized] = React.useState(false);

  const navigate = useNavigate();

  const schema = yup.object({
    name: yup.string(),
    status: yup.string(),
  });

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

  // const getManagerProducers = async () => {
  //   try {
  //     const res = await getOnePermissionsForManager(
  //       localStorage.getItem('user')
  //     );
  //     if (!res.error) {
  //       let array = [];
  //       array = JSON.parse(res.model.member_ids) || [];
  //       setManagerMember(array);
  //     }
  //   } catch (error) {}
  // };

  const getAllProducers = async () => {
    try {
      const result = await getAllMembersForManager(
        localStorage.getItem("user")
      );

      if (!result.error) {
        if (result.list.length > 0) {
          let list = result.list;

          list = list.map((row) => {
            row.user_name = row.first_name + " " + row.last_name;
            return { value: row.id, label: row.user_name };
          });

          let forSelect = [];
          if (list.length > 0) {
            list.map((row, i) => {
              forSelect.push({
                value: row.value,
                label: row?.label,
              });
            });
          }

          setProducersForSelect(forSelect);
        }
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  function updatePageSize(limit) {
    (async function () {
      setPageSize(limit);
      await getData(1, limit);
    })();
    localStorage.setItem("mixSeasonPageSize", 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
      // );
      console.log(pageSizeFromLocalStorage, pageSize);
      await getData(
        currentPage + 1,
        pageSizeFromLocalStorage ? Number(pageSizeFromLocalStorage) : pageSize
      );
    })();
  }

  async function getData(
    pageNum,
    limitNum,
    filter,
    selectedProd = selectedProducers
  ) {
    try {
      let result;
      if (selectedProd.length > 0) {
        result = await retrieveAllForMixSeasonForManager(
          pageNum,
          limitNum,
          removeKeysWhenValueIsNull({
            ...filter,
            member_ids: selectedProd.map((elem) => elem.value) ?? null,
          })
        );
      } else {
        result = await retrieveAllForMixSeasonForManager(
          pageNum,
          limitNum,
          removeKeysWhenValueIsNull({
            ...filter,
            member_ids:
              producersForSelect.length > 0
                ? producersForSelect.map((elem) => elem.value)
                : null,
          })
        );
      }

      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);
      setLoading(false);
    } catch (error) {
      setLoading(false);
      tokenExpireError(dispatch, error.message);
    }
  }

  const resetForm = async () => {
    reset();
    localStorage.setItem("mixSeasonPageSize", 10);
    setPageSize(10);
    setSelectedProducers([]);
    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));
  };

  // First useEffect - only handle path setting and producer loading
  React.useEffect(() => {
    globalDispatch({
      type: "SETPATH",
      payload: {
        path: "mix-seasons",
      },
    });

    // Load producers first
    const initProducers = async () => {
      try {
        setLoading(true);
        await getAllProducers();
        setProducersInitialized(true);
      } catch (error) {
        tokenExpireError(dispatch, error.message);
      }
    };

    initProducers();
  }, []);

  // Second useEffect - handle data loading only after producers are initialized
  React.useEffect(() => {
    if (producersInitialized) {
      const loadData = async () => {
        try {
          const size = pageSizeFromLocalStorage
            ? Number(pageSizeFromLocalStorage)
            : pageSize;
          await getData(1, size);
        } catch (error) {
          tokenExpireError(dispatch, error.message);
        }
      };

      loadData();
    }
  }, [producersInitialized]);

  const handleSelectedProducers = (names) => {
    if (names.length === 0) {
      setSelectedProducers([]);
      // localStorage.setItem('projectProducers', JSON.stringify(''));
      // setCachedProjectProducers([]);
    } else {
      setSelectedProducers(names);
      // localStorage.setItem('projectProducers', JSON.stringify(names));
      // setCachedProjectProducers(names);
    }

    // kks

    // if (names?.length < selectedProducers.length) {
    //   setReFilter(!reFilter);
    // }
  };

  const selectProducersRef = React.useRef(null);

  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">
                {/* Producer Filter */}
                <div className="w-64">
                  <FormMultiSelect
                    selectRef={selectProducersRef}
                    values={selectedProducers}
                    onValuesChange={handleSelectedProducers}
                    options={producersForSelect}
                    placeholder="Producers"
                  />
                </div>

                {/* Season Name Input */}
                <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 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"
                />

                {/* Status Select */}
                <CustomSelect2
                  register={register}
                  name="status"
                  label="Status"
                  placeholder="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 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>

              {!loading && currentTableData.length > 0 ? (
                <tbody className="cursor-pointer text-white">
                  {currentTableData.map((row, i) => (
                    <tr
                      key={i}
                      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>
              ) : loading && 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>
              ) : !loading && 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 && !loading && (
          <div className="w-full px-4 py-10 md:px-6 2xl:px-9">
            <PaginationBar
              callDataAgain={callDataAgain}
              currentPage={currentPage}
              pageCount={pageCount}
              pageSize={pageSize}
              canPreviousPage={canPreviousPage}
              canNextPage={canNextPage}
              updatePageSize={updatePageSize}
              previousPage={previousPage}
              nextPage={nextPage}
              dataTotal={dataTotal}
              setCurrentPage={setPage}
            />
          </div>
        )}
      </div>
    </div>
  );
};

export default ManagerListMixSeasonPage;
