import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { yupResolver } from "@hookform/resolvers/yup";
import AddButton from "Components/AddButton";
import ExportButton from "Components/ExportButton";
import PaginationBar from "Components/PaginationBar";
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 { GlobalContext, showToast } from "../../globalContext";
import { getNonNullValue, removeKeysWhenValueIsNull } from "../../utils/utils";

import ManagerListClientRow from "Components/manager/managerListClientRow";
import { ClipLoader } from "react-spinners";
import {
  getAllMembersForManager,
  retrieveAllForClientForManager,
} from "Src/services/managerServices";
import CustomSelect2 from "Components/CustomSelect2";

const columns = [
  {
    header: "Program",
    accessor: "program",
    isSorted: false,
    isSortedDesc: false,
    mappingExist: false,
    mappings: {},
  },
  {
    header: "Position",
    accessor: "position",
    isSorted: false,
    isSortedDesc: false,
    mappingExist: false,
    mappings: {},
  },
  {
    header: "Producers",
    accessor: "member_name",
    isSorted: false,
    isSortedDesc: false,
    mappingExist: false,
    mappings: {},
  },
  {
    header: "Name",
    accessor: "name",
    isSorted: false,
    isSortedDesc: false,
    mappingExist: false,
    mappings: {},
  },
  {
    header: "Email",
    accessor: "email",
    isSorted: false,
    isSortedDesc: false,
    mappingExist: false,
    mappings: {},
  },
  {
    header: "Phone",
    accessor: "phone",
    isSorted: false,
    isSortedDesc: false,
    mappingExist: false,
    mappings: {},
  },
];

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

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

  const [clients, setClients] = React.useState([]);
  const [currentProducer, setCurrentProducer] = React.useState("");

  // Check if pageSize exists in local storage
  const pageSizeFromLocalStorage = localStorage.getItem("clientPageSize");
  const [producersForSelect, setProducersForSelect] = React.useState([]);

  // 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({
    program: yup.string(),
    position: yup.string(),
    name: yup.string(),
    email: yup.string(),
    phone: yup.string(),
    producer: yup.string(),
  });

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

  const selectedProducer = watch("producer");

  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 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 () {
      setPageSize(limit);
      await getData(1, limit);
    })();
    localStorage.setItem("clientPageSize", 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 <= pageCount ? currentPage + 1 : 0,
      //   pageSize
      // );
      await getData(
        page,
        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
      );
    })();
  }

  async function getData(
    pageNum,
    limitNum,
    filter,
    selectedProd = selectedProducer,
    search = false
  ) {
    try {
      setLoading(true);
      let result1;

      console.log(filter);

      if (search) {
        result1 = await retrieveAllForClientForManager(
          pageNum,
          limitNum,
          removeKeysWhenValueIsNull({
            ...filter,
          })
        );
      } else {
        result1 = await retrieveAllForClientForManager(
          pageNum,
          limitNum,
          removeKeysWhenValueIsNull({
            ...filter,
            member_ids:
              selectedProd.length > 0
                ? [selectedProd]
                : producersForSelect.length > 0
                ? producersForSelect.map((elem) => elem.value)
                : null,
          })
        );
      }
      setCurrentProducer(selectedProd);

      // Combine list arrays from both results
      const combinedList = [...result1.list];

      const { total, limit, num_pages, page } = result1;

      // sort list by name alphabetically
      combinedList.sort((a, b) => {
        if (a.program < b.program) {
          return -1;
        }
        return 1;
      });

      const uniqueIds = new Set();

      // Filter combinedList to remove objects with duplicate IDs
      const filteredList = combinedList.filter((item) => {
        // If the ID is not in the uniqueIds set, add it and return true (to keep the item)
        if (!uniqueIds.has(item.id)) {
          uniqueIds.add(item.id);
          return true;
        }
        // If the ID is already in the uniqueIds set, return false (to remove the item)
        return false;
      });

      setCurrentTableData(filteredList);
      setClients(filteredList);
      // 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("clientPageSize", 10);
    setPageSize(10);
    await setValue("producer", "");
    await getData(1, pageSize, {}, []);
  };

  const handleCopyAllEmails = (e) => {
    e.preventDefault();
    let emails = "";
    clients.forEach((client) => {
      emails += client.email + "; ";
    });
    navigator.clipboard.writeText(emails);
    showToast(globalDispatch, "Emails copied to clipboard", 5000);
  };

  const handleExportCSVFromTable = () => {
    const headers = [];

    for (let key in clients[0]) {
      let headerLabel = key;
      if (key === "has_auth") {
        headerLabel = "Enabled Login";
      }
      if (
        key !== "id" &&
        key !== "user_id" &&
        key !== "create_at" &&
        key !== "update_at" &&
        key !== "member_two_user_id"
      ) {
        headers.push(
          headerLabel.charAt(0).toUpperCase() + headerLabel.slice(1)
        );
      }
    }

    // push the headers to csv at the first row
    const csv = [headers.join(",")];

    // push the data to csv
    for (let i = 0; i < clients.length; i++) {
      const row = [];

      for (const key in clients[i]) {
        let value = clients[i][key];
        if (key === "has_auth") {
          value = value === 1 ? "true" : "false";
        }
        if (
          key !== "id" &&
          key !== "user_id" &&
          key !== "create_at" &&
          key !== "update_at" &&
          key !== "member_two_user_id"
        ) {
          row.push(value);
        }
      }
      csv.push(row.join(","));
    }

    // Download CSV file
    let currentDateTime = new Date();
    downloadCSV(csv.join("\n"), "Client_list_" + currentDateTime + ".csv");
  };

  const downloadCSV = (csv, filename) => {
    let csvFile;
    let downloadLink;
    // CSV file
    csvFile = new Blob([csv], { type: "text/csv" });
    // Download link
    downloadLink = document.createElement("a");
    // File name
    downloadLink.download = filename;
    // Create a link to the file
    downloadLink.href = window.URL.createObjectURL(csvFile);
    // Hide download link
    downloadLink.style.display = "none";
    // Add the link to DOM
    document.body.appendChild(downloadLink);
    // Click download link
    downloadLink.click();
  };

  const onSubmit = async (_data) => {
    let program = getNonNullValue(_data.program);
    let position = getNonNullValue(_data.position);
    let name = getNonNullValue(_data.name);
    let email = getNonNullValue(_data.email);
    let phone = getNonNullValue(_data.phone);
    let producer = getNonNullValue(_data.producer);
    let filter = {
      program: program,
      position: position,
      name: name,
      email: email,
      phone: phone,
    };

    if (!producer && (position || name || phone || email || program)) {
      await getData(
        1,
        pageSize,
        removeKeysWhenValueIsNull({
          ...filter,
          member_ids:
            producersForSelect.length <= 0
              ? null
              : producersForSelect.map((elem) => elem.value),
        }),

        true
      );
    } else {
      await getData(1, pageSize, removeKeysWhenValueIsNull(filter));
    }
  };

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

    // Combine initialization into a single async function
    const initializePage = async () => {
      try {
        setLoading(true);
        await getAllProducers();
        const pageSize = pageSizeFromLocalStorage
          ? Number(pageSizeFromLocalStorage)
          : 10;
        await getData(1, pageSize);
      } finally {
        setLoading(false);
      }
    };

    initializePage();
  }, []);

  React.useEffect(() => {
    if (producersForSelect.length > 0) {
      // Only run if producers are loaded
      const loadData = async () => {
        try {
          setLoading(true);
          const size = pageSizeFromLocalStorage
            ? Number(pageSizeFromLocalStorage)
            : pageSize;

          await getData(
            1,
            size,
            removeKeysWhenValueIsNull({
              member_ids:
                producersForSelect.length <= 0
                  ? null
                  : producersForSelect.map((elem) => elem.value),
            })
          );
        } finally {
          setLoading(false);
        }
      };

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

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

  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">
            Clients
          </h4>
          <div className="flex items-center gap-2">
            <AddButton link={`/${authState.role}/add-client`} />
            {clients && clients.length > 0 && (
              <>
                <button
                  onClick={handleCopyAllEmails}
                  className="inline-flex h-[32px] w-[32px] items-center justify-center rounded bg-primary text-white hover:bg-opacity-90"
                >
                  <FontAwesomeIcon
                    icon="fa-solid fa-clipboard"
                    className="h-4 w-4"
                  />
                </button>
                <ExportButton onClick={handleExportCSVFromTable} />
              </>
            )}
          </div>
        </div>

        {/* Search Form 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)} className="">
              <div className="flex items-center gap-3">
                <CustomSelect2
                  register={register}
                  name="producer"
                  label="Producer"
                  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 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 Producers</option>
                  {producersForSelect.map((elem) => (
                    <option key={elem.value} value={elem.value}>
                      {elem.label}
                    </option>
                  ))}
                </CustomSelect2>
                <input
                  type="text"
                  placeholder="Program"
                  {...register("program")}
                  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"
                />
                <input
                  type="text"
                  placeholder="Position"
                  {...register("position")}
                  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"
                />
                <input
                  type="text"
                  placeholder="Name"
                  {...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"
                />
              </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>
          </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={`cursor-pointer px-4 py-3 text-left text-xs font-medium uppercase tracking-wider 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 Clients...
                      </span>
                    </td>
                  </tr>
                </tbody>
              ) : currentTableData.length > 0 ? (
                <tbody className="cursor-pointer text-white">
                  {currentTableData.map((row, i) => (
                    <ManagerListClientRow
                      key={i}
                      row={row}
                      i={i}
                      columns={columns}
                      selectedProducers={currentProducer}
                    />
                  ))}
                </tbody>
              ) : (
                <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>

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

export default ManagerListClientPage;
