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 { retrieveAllMixTypesAPI } from "Src/services/mixTypeServices";
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 } from "../utils/utils";
import CustomSelect2 from "../components/CustomSelect2";

const COLORS = [
  {
    id: 1,
    color: "#6CC551",
    name: "Green",
  },
  {
    id: 2,
    color: "#197BBD",
    name: "Blue",
  },
  {
    id: 3,
    color: "#F3A738",
    name: "Gold",
  },
  {
    id: 4,
    color: "#C0C0C0",
    name: "Gray",
  },
  {
    id: 5,
    color: "#8A2BE2",
    name: "Purple",
  },
  {
    id: 6,
    color: "#FF91AF",
    name: "Pink",
  },
  {
    id: 7,
    color: "#00FFFF",
    name: "Cyan",
  },
  {
    id: 8,
    color: "#B31B1B",
    name: "Red",
  },
  {
    id: 9,
    color: "#FF7F50",
    name: "Coral",
  },
];

const columns = [
  {
    header: "Name",
    accessor: "name",
    isSorted: false,
    isSortedDesc: false,
    mappingExist: false,
    mappings: {},
  },
  {
    header: "Voiceover",
    accessor: "is_voiceover",
    isSorted: false,
    isSortedDesc: false,
    mappingExist: true,
    mappings: {
      0: "No",
      1: "Yes",
    },
  },
  {
    header: "Voiceover Count",
    accessor: "voiceover",
    isSorted: false,
    isSortedDesc: false,
    mappingExist: false,
    mappings: {},
  },
  {
    header: "Song",
    accessor: "is_song",
    isSorted: false,
    isSortedDesc: false,
    mappingExist: true,
    mappings: {
      0: "No",
      1: "Yes",
    },
  },
  {
    header: "Song Count",
    accessor: "song",
    isSorted: false,
    isSortedDesc: false,
    mappingExist: false,
    mappings: {},
  },
  {
    header: "Tracking",
    accessor: "is_tracking",
    isSorted: false,
    isSortedDesc: false,
    mappingExist: true,
    mappings: {
      0: "No",
      1: "Yes",
    },
  },
  {
    header: "Tracking Count",
    accessor: "tracking",
    isSorted: false,
    isSortedDesc: false,
    mappingExist: false,
    mappings: {},
  },
  {
    header: "Color",
    accessor: "color",
    isSorted: false,
    isSortedDesc: false,
    mappingExist: false,
    mappings: {},
  },
  {
    header: "Price",
    accessor: "price",
    isSorted: false,
    isSortedDesc: false,
    mappingExist: false,
    mappings: {},
  },
];

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

  const [currentTableData, setCurrentTableData] = React.useState([]);
  const [searchResult, setSearchResult] = 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 [loading, setLoading] = React.useState(false);
  const [isLoading, setIsLoading] = React.useState(false);
  console.log(currentTableData, isLoading);

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

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

  const navigate = useNavigate();
  console.log(pageSize);

  const schema = yup.object({
    name: yup.string(),
    is_voiceover: yup.string(),
    is_song: yup.string(),
    price: yup.string(),
    voiceover: yup.string(),
    song: yup.string(),
  });
  const {
    register,
    handleSubmit,
    setError,
    reset,
    formState: { errors },
  } = useForm({
    resolver: yupResolver(schema),
  });

  function onSort(columnIndex) {
    if (columns[columnIndex].isSorted) {
      columns[columnIndex].isSortedDesc = !columns[columnIndex].isSortedDesc;
    } else {
      columns.map((i) => (i.isSorted = false));
      columns.map((i) => (i.isSortedDesc = false));
      columns[columnIndex].isSorted = true;
    }

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

  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("mixTypePageSize", 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 retrieveAllMixTypesAPI(pageNum, limitNum, filter);
      const { list, total, limit, num_pages, page } = result;
      setCurrentTableData(list);
      setSearchResult(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("mixTypePageSize", 10);
    setPageSize(10);
    await getData(1, pageSize);
  };

  const onSubmit = (_data) => {
    let name = getNonNullValue(_data.name);
    let is_voiceover = getNonNullValue(_data.is_voiceover);
    let is_song = getNonNullValue(_data.is_song);
    let is_tracking = getNonNullValue(_data.is_tracking);
    let color = getNonNullValue(_data.color);
    let price = getNonNullValue(_data.price);
    let filter = {
      name: name,
      is_voiceover: is_voiceover,
      is_song: is_song,
      is_tracking: is_tracking,
      color: color,
      price: price,
    };
    getData(1, pageSize, removeKeysWhenValueIsNull(filter));
  };

  const handleSearch = (e) => {
    // e.preventDefault();
    const keyword = e.target.value;
    if (keyword !== "") {
      const filterSearch = currentTableData.filter((item) => {
        return item.name.toLowerCase().includes(keyword.toLowerCase());
      });
      setSearchResult(filterSearch);
    } else {
      setSearchResult(currentTableData);
    }
  };

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

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

    // (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 dark:border-strokedark dark: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 Types
          </h4>
          <AddButton link={`/${authState.role}/add-mix-type`} />
        </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 flex-wrap items-center gap-3">
                {/* Name Input */}
                <div className="flex w-[16%] flex-col">
                  <label className="mb-1.5 text-sm font-medium text-white">
                    Name
                  </label>
                  <input
                    type="text"
                    placeholder="name"
                    {...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>

                {/* Voiceover Select */}
                <div className="flex w-[16%] flex-col">
                  <label className="mb-1.5 text-sm font-medium text-white">
                    Voiceover
                  </label>
                  <CustomSelect2
                    register={register}
                    name="is_voiceover"
                    label="Select Voiceover"
                    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"
                  >
                    <option value="">Select Voiceover</option>
                    <option value="1">Yes</option>
                    <option value="0">No</option>
                  </CustomSelect2>
                </div>

                {/* Song Select */}
                <div className="flex w-[16%] flex-col">
                  <label className="mb-1.5 text-sm font-medium text-white">
                    Song
                  </label>
                  <CustomSelect2
                    register={register}
                    name="is_song"
                    label="Select Song"
                    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"
                  >
                    <option value="">Select Song</option>
                    <option value="1">Yes</option>
                    <option value="0">No</option>
                  </CustomSelect2>
                </div>

                {/* Tracking Select */}
                <div className="flex w-[16%] flex-col">
                  <label className="mb-1.5 text-sm font-medium text-white">
                    Tracking
                  </label>
                  <CustomSelect2
                    register={register}
                    name="is_tracking"
                    label="Select Tracking"
                    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"
                  >
                    <option value="">Select Tracking</option>
                    <option value="1">Yes</option>
                    <option value="0">No</option>
                  </CustomSelect2>
                </div>

                {/* Color Select */}
                <div className="flex w-[16%] flex-col">
                  <label className="mb-1.5 text-sm font-medium text-white">
                    Color
                  </label>
                  <CustomSelect2
                    register={register}
                    name="color"
                    label="Select Color"
                    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"
                  >
                    <option value="">Select Color</option>
                    {COLORS.map((color) => (
                      <option key={color.id} value={color.name}>
                        {color.name}
                      </option>
                    ))}
                  </CustomSelect2>
                </div>
                {/* Price Input */}
                <div className="flex w-[16%] flex-col">
                  <label className="mb-1.5 text-sm font-medium text-white">
                    Price
                  </label>
                  <input
                    type="text"
                    placeholder="Price"
                    {...register("price")}
                    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>
              </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}
                      onClick={() => onSort(i)}
                      className={`whitespace-nowrap px-3 py-3 text-left text-xs font-medium uppercase tracking-wider text-bodydark1 ${
                        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">
                  {searchResult.map((row, i) => (
                    <tr
                      key={i}
                      onClick={() =>
                        navigate(`/${authState.role}/view-mix-type/${row.id}`)
                      }
                      className="border-b border-strokedark hover:bg-primary/5"
                    >
                      {columns.map((cell, index) => (
                        <td
                          key={index}
                          className={`whitespace-nowrap px-3 py-4 ${
                            index === 0
                              ? "text-bodydark1 xl:pl-6 2xl:pl-9"
                              : "text-bodydark"
                          }`}
                        >
                          {cell.accessor === "color" ? (
                            <div className="flex items-center gap-3">
                              <div
                                className="h-6 w-6 rounded-full"
                                style={{
                                  backgroundColor: COLORS.find(
                                    (color) =>
                                      color.color === row[cell.accessor]
                                  )?.color,
                                }}
                              ></div>
                              {COLORS.find(
                                (color) => color.color === row[cell.accessor]
                              )?.name || row[cell.accessor]}
                            </div>
                          ) : 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 Types...
                      </span>
                    </td>
                  </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>
              ) : 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 ListMixTypePage;
