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 { ClipLoader } from "react-spinners";
import { retrieveAllForClientForAdmin } from "Src/services/clientService";
import { retrieveAllUserAPI } from "Src/services/userService";
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: "Producer",
    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 AdminListClientPage = () => {
  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 [clients, setClients] = React.useState([]);

  // Check if pageSize exists in local storage
  const pageSizeFromLocalStorage = localStorage.getItem("clientPageSize");
  const [producersForSelect, setProducersForSelect] = React.useState([]);
  const [currentProducer, setCurrentProducer] = React.useState("");
  const [loading, setLoading] = React.useState(true);
  const [producersInitialized, setProducersInitialized] = React.useState(false);
  // 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,
    reset,
    watch,
    setValue,
    formState: { errors },
  } = useForm({
    resolver: yupResolver(schema),
  });

  const retrieveAllUsers = async () => {
    try {
      let filter = {
        role: "member",
      };
      const result = await retrieveAllUserAPI(1, 10000, filter);
      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);
    }
  };

  const selectedProducer = watch("producer");

  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 callDataAgain(page) {
    (async function () {
      // await getData(currentPage - 1 > 0 ? currentPage - 1 : 0, pageSize);
      await getData(
        page,
        pageSizeFromLocalStorage ? Number(pageSizeFromLocalStorage) : pageSize
      );
    })();
  }

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

  async function getData(
    pageNum,
    limitNum,
    filter,
    selectedProd = selectedProducer,
    search = false
  ) {
    try {
      setLoading(true);
      let result;
      if (search) {
        result = await retrieveAllForClientForAdmin(
          pageNum,
          limitNum,
          removeKeysWhenValueIsNull({
            ...filter,
          })
        );
      } else {
        result = await retrieveAllForClientForAdmin(
          pageNum,
          limitNum,
          removeKeysWhenValueIsNull({
            ...filter,
            member_ids: selectedProd.length > 0 ? [selectedProd] : null,
          })
        );
      }
      setCurrentProducer(selectedProd);

      const { list, total, limit, num_pages, page } = result;

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

      setClients(list);

      setCurrentTableData(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 () => {
    await getData(1, pageSize, {}, []);
    reset();
    setValue("producer", "");
    localStorage.setItem("clientPageSize", 10);
    setPageSize(10);
  };

  // const getAllClient = async () => {
  //   try {
  //     const result = await getAllClientAPI();
  //     if (!result.error) {
  //       setClients(result.list);
  //     } else {
  //       showToast(dispatch, 'Error exporting to CSV', 5000, 'error');
  //     }
  //   } catch (error) {
  //
  //     tokenExpireError(dispatch, error.message);
  //   }
  // };

  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 (const key in clients[0]) {
      if (
        key !== "id" &&
        key !== "user_id" &&
        key !== "create_at" &&
        key !== "update_at"
      ) {
        headers.push(key.charAt(0).toUpperCase() + key.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]) {
        if (
          key !== "id" &&
          key !== "user_id" &&
          key !== "create_at" &&
          key !== "update_at"
        ) {
          row.push(clients[i][key]);
        }
      }
      csv.push(row.join(","));
    }

    // Download CSV file
    let currentDateTime = new Date();
    downloadCSV(csv.join("\n"), "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,
        }),
        true
      );
    } else {
      await getData(1, pageSize, removeKeysWhenValueIsNull(filter));
    }
  };

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

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

    initProducers();
  }, []);

  React.useEffect(() => {
    if (producersInitialized) {
      const loadData = async () => {
        try {
          setLoading(true);
          const size = pageSizeFromLocalStorage
            ? Number(pageSizeFromLocalStorage)
            : pageSize;
          await getData(1, size);
        } finally {
          setLoading(false);
        }
      };

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

  console.log(loading, currentTableData);

  return (
    <div className="max-w-screen h-full p-4 md:p-4 lg:p-6 xl:p-8">
      <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">
            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">
          <form onSubmit={handleSubmit(onSubmit)}>
            <div>
              <div className="flex flex-wrap items-center gap-3">
                {/* Producer Select */}
                <div className="flex flex-col">
                  <label className="mb-1.5 text-sm font-medium text-white">
                    Producer
                  </label>
                  <CustomSelect2
                    register={register}
                    name="producer"
                    label="Select Producers"
                    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 Producers</option>
                    {producersForSelect.map((elem) => (
                      <option key={elem.value} value={elem.value}>
                        {elem.label}
                      </option>
                    ))}
                  </CustomSelect2>
                </div>

                {/* Program Input */}
                <div className="flex flex-col">
                  <label className="mb-1.5 text-sm font-medium text-white">
                    Program
                  </label>
                  <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:text-bodydark focus:border-primary active:border-primary disabled:cursor-default disabled:bg-whiter dark:border-form-strokedark dark:bg-form-input"
                  />
                </div>

                {/* Position Input */}
                <div className="flex flex-col">
                  <label className="mb-1.5 text-sm font-medium text-white">
                    Position
                  </label>
                  <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:text-bodydark focus:border-primary active:border-primary disabled:cursor-default disabled:bg-whiter dark:border-form-strokedark dark:bg-form-input"
                  />
                </div>

                {/* Name Input */}
                <div className="flex 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-64 rounded border-[1.5px] border-form-strokedark bg-form-input px-3 py-2 text-sm outline-none transition placeholder:text-bodydark focus:border-primary active:border-primary disabled:cursor-default disabled:bg-whiter dark:border-form-strokedark dark:bg-form-input"
                  />
                </div>

                {/* Email Input */}
                <div className="flex flex-col">
                  <label className="mb-1.5 text-sm font-medium text-white">
                    Email
                  </label>
                  <input
                    type="text"
                    placeholder="email"
                    {...register("email")}
                    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:text-bodydark focus:border-primary active:border-primary disabled:cursor-default disabled:bg-whiter dark:border-form-strokedark dark:bg-form-input"
                  />
                </div>
              </div>

              {/* Action Buttons */}
              <div className="mt-4 flex gap-3">
                <button
                  type="submit"
                  className="inline-flex items-center justify-center rounded 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 items-center justify-center rounded bg-danger px-4 py-2 text-sm font-medium text-white hover:bg-opacity-90"
                >
                  Reset
                </button>
              </div>
            </div>
          </form>
        </div>

        {/* Table Section */}
        <div className="px-4 md:px-6 2xl:px-9">
          <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>
              )}

              {!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-client/${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>

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

export default AdminListClientPage;
