import { yupResolver } from "@hookform/resolvers/yup";
import FormMultiSelect from "Components/FormMultiSelect";
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 { retrieveAllUserAPI } from "Src/services/userService";
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: "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 AdminListMixSeasonPage = () => {
  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(true);

  // 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 [producersForSelect, setProducersForSelect] = React.useState([]);
  const [selectedProducers, setSelectedProducers] = React.useState([]);
  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 getAllProducers = async () => {
    try {
      const result = await retrieveAllUserAPI(1, 10000, { role: "member" });

      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 nextPage() {
    (async function () {
      // await getData(
      //   currentPage + 1 <= pageCount ? currentPage + 1 : 0,
      //   pageSize
      // );
      await getData(
        currentPage + 1,
        pageSizeFromLocalStorage ? Number(pageSizeFromLocalStorage) : pageSize
      );
    })();
  }
  console.log(selectedProducers);

  async function getData(
    pageNum,
    limitNum,
    filter,
    selectedProd = selectedProducers
  ) {
    try {
      setLoading(true);
      console.log(selectedProd);
      const result = await retrieveAllMixSeasonsAPI(
        pageNum,
        limitNum,
        removeKeysWhenValueIsNull({
          ...filter,
          user_id:
            selectedProd.length <= 0
              ? null
              : selectedProd.map((elem) => elem.value),
        })
      );
      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) {
      tokenExpireError(dispatch, error.message);
    }
  }

  const handleSelectedProducers = async (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) {
      await getData(1, pageSize, {}, []);
    }
  };

  const resetForm = async () => {
    reset();
    setSelectedProducers([]);
    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), selectedProducers);
  };

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

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

    initProducers();
  }, []);

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

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

  const selectProducersRef = React.useRef(null);

  console.log(loading, "sshhhshs");
  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 onSubmit={handleSubmit(onSubmit)}>
              <div>
                <div className="flex items-center gap-3">
                  {/* Producer Filter */}
                  <div className="w-64">
                    <label
                      htmlFor="producers"
                      className="mb-2 block text-sm text-white"
                    >
                      Producers
                    </label>
                    <FormMultiSelect
                      id="producers"
                      selectRef={selectProducersRef}
                      values={selectedProducers}
                      onValuesChange={handleSelectedProducers}
                      options={producersForSelect}
                      placeholder="Producers"
                    />
                  </div>

                  {/* Season Name Input */}
                  <div className="w-64">
                    <label
                      htmlFor="season_name"
                      className="mb-2 block text-sm text-white"
                    >
                      Season Name
                    </label>
                    <input
                      id="season_name"
                      type="text"
                      placeholder="Season"
                      {...register("name")}
                      className="h-[36px] w-full 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>

                  {/* Status Select */}
                  <div className="w-64">
                    <label
                      htmlFor="status"
                      className="mb-2 block text-sm 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 focus:border-primary active:border-primary disabled:cursor-default disabled:bg-whiter dark:border-form-strokedark dark:bg-form-input"
                    >
                      <option value="">Select Status</option>
                      <option value="1">Active</option>
                      <option value="0">Inactive</option>
                    </CustomSelect2>
                  </div>
                </div>

                {/* Action Buttons */}
                <div className="mt-4 flex items-center gap-3">
                  <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>
              </div>
            </form>
          </div>
        </div>

        {/* Table Section */}
        <div className="border-b border-strokedark px-4 py-4 sm:px-6 2xl:px-9">
          <div className="min-h-[150px] max-w-full overflow-x-auto">
            <table className="w-full table-auto">
              <thead>
                <tr className="bg-meta-4">
                  {columns.map((column, i) => (
                    <th
                      key={i}
                      className={`px-4 py-3 text-left font-medium text-white ${
                        i == 0 && "2xl:pl-9"
                      }`}
                    >
                      {column.header}
                      <span>
                        {column.isSorted
                          ? column.isSortedDesc
                            ? " ▼"
                            : " ▲"
                          : ""}
                      </span>
                    </th>
                  ))}
                </tr>
              </thead>

              {loading && (
                <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 className="cursor-pointer text-white">
                  {currentTableData.map((row, i) => (
                    <tr
                      key={i}
                      className="border-b border-strokedark hover:bg-primary/5"
                      onClick={() => {
                        navigate(
                          `/${authState.role}/view-mix-season/${row.id}`,
                          {
                            state: row,
                          }
                        );
                      }}
                    >
                      {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="relative top-[10px] m-4 p-4 font-semibold text-white">
                        No data found
                      </span>
                    </td>
                  </tr>
                </tbody>
              )}
            </table>
          </div>
        </div>

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

export default AdminListMixSeasonPage;
