import React, { useEffect } from "react";
import { AuthContext, tokenExpireError } from "../authContext";
import { useForm } from "react-hook-form";
import { useNavigate } from "react-router-dom";
import * as yup from "yup";
import { yupResolver } from "@hookform/resolvers/yup";
import moment from "moment";
import { GlobalContext, showToast } from "../globalContext";
import { getNonNullValue, removeKeysWhenValueIsNull } from "../utils/utils";
import PaginationBar from "../components/PaginationBar";
import AddButton from "../components/AddButton";
import { retrieveAllEmployeeAPI } from "Src/services/employeeService";
import Spinner from "Components/Spinner";
import { DateRangePicker } from "react-dates";
import { ClipLoader } from "react-spinners";
import CustomSelect from "../components/CustomSelect";
import CustomSelect2 from "Components/CustomSelect2";

const columns = [
  {
    header: "Name",
    accessor: "name",
    isSorted: false,
    isSortedDesc: false,
    mappingExist: false,
    mappings: {},
  },
  {
    header: "Email",
    accessor: "email",
    isSorted: false,
    isSortedDesc: false,
    mappingExist: false,
    mappings: {},
  },

  {
    header: "Writer",
    accessor: "is_writer",
    isSorted: false,
    isSortedDesc: false,
    mappingExist: true,
    mappings: {
      0: "No",
      1: "Yes",
      null: "No",
    },
  },
  {
    header: "Writer Cost",
    accessor: "writer_cost",
    isSorted: false,
    isSortedDesc: false,
    mappingExist: false,
    mappings: {},
  },
  {
    header: "Artist",
    accessor: "is_artist",
    isSorted: false,
    isSortedDesc: false,
    mappingExist: true,
    mappings: {
      0: "No",
      1: "Yes",
      null: "No",
    },
  },

  {
    header: "Artist Cost",
    accessor: "artist_cost",
    isSorted: false,
    isSortedDesc: false,
    mappingExist: false,
    mappings: {},
  },
  {
    header: "Gender",
    accessor: "gender",
    isSorted: false,
    isSortedDesc: false,
    mappingExist: false,
    mappings: {},
  },
  {
    header: "Engineer",
    accessor: "is_engineer",
    isSorted: false,
    isSortedDesc: false,
    mappingExist: true,
    mappings: {
      0: "No",
      1: "Yes",
      null: "No",
    },
  },
  {
    header: "Engineer Cost",
    accessor: "engineer_cost",
    isSorted: false,
    isSortedDesc: false,
    mappingExist: false,
    mappings: {},
  },
  {
    header: "Producer",
    accessor: "is_producer",
    isSorted: false,
    isSortedDesc: false,
    mappingExist: true,
    mappings: {
      0: "No",
      1: "Yes",
      null: "No",
    },
  },
  {
    header: "Producer Cost",
    accessor: "producer_cost",
    isSorted: false,
    isSortedDesc: false,
    mappingExist: false,
    mappings: {},
  },
  {
    header: "W-9",
    accessor: "w_nine",
    isSorted: false,
    isSortedDesc: false,
    mappingExist: false,
    mappings: {},
  },
  // {
  //   header: 'Total Earning (as writer)',
  //   accessor: 'writer_earnings',
  //   isSorted: false,
  //   isSortedDesc: false,
  //   mappingExist: false,
  //   mappings: {},
  // },
  // {
  //   header: 'Total Earning (as artist)',
  //   accessor: 'artist_earnings',
  //   isSorted: false,
  //   isSortedDesc: false,
  //   mappingExist: false,
  //   mappings: {},
  // },
  // {
  //   header: 'Total Earning (as engineer)',
  //   accessor: 'engineer_earnings',
  //   isSorted: false,
  //   isSortedDesc: false,
  //   mappingExist: false,
  //   mappings: {},
  // },
  // {
  //   header: 'Total Earning (as producer)',
  //   accessor: 'producer_earnings',
  //   isSorted: false,
  //   isSortedDesc: false,
  //   mappingExist: false,
  //   mappings: {},
  // },
  {
    header: "Total Earnings",
    accessor: "total_earnings",
    isSorted: false,
    isSortedDesc: false,
    mappingExist: false,
    mappings: {},
  },
];

const userTypes = [
  {
    id: 1,
    name: "Writer",
  },
  {
    id: 2,
    name: "Artist",
  },
  {
    id: 3,
    name: "Engineer",
  },
  {
    id: 4,
    name: "Producer",
  },
];

const ListEmployeePage = () => {
  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(false);

  // Check if pageSize exists in local storage
  const pageSizeFromLocalStorage = localStorage.getItem("employeePageSize");
  const [focusedInput, setFocusedInput] = React.useState(null);

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

  console.log(pageSize, "sjjsjs");

  const navigate = useNavigate();

  const schema = yup.object({
    name: yup.string(),
    email: yup.string(),
    is_writer: yup.string(),
    writer_cost: yup.string(),
    is_artist: yup.string(),
    artist_cost: yup.string(),
    is_engineer: yup.string(),
    engineer_cost: yup.string(),
    is_producer: yup.string(),
    producer_cost: yup.string(),
    w_nine: yup.string(),
    date_start: yup.string(),
    date_end: yup.string(),
  });
  const {
    register,
    handleSubmit,
    setError,
    setValue,
    reset,
    watch,
    formState: { errors },
  } = useForm({
    resolver: yupResolver(schema),
  });

  const dateStart = watch("date_start");
  const dateEnd = watch("date_end");

  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("employeePageSize", 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) {
    try {
      const result = await retrieveAllEmployeeAPI(pageNum, limitNum, filter);
      const { list, total, limit, num_pages, page } = result;
      setCurrentTableData(list);

      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("employeePageSize", 10);
    setPageSize(10);
    await getData(1, pageSize);
  };

  const onSubmit = (_data) => {
    let name = getNonNullValue(_data.name);
    let email = getNonNullValue(_data.email);
    let userType = _data.user_type ? Number(_data.user_type) : null;
    let startDate = _data.date_start
      ? moment(_data.date_start).format("YYYY-MM-DD")
      : null;
    let endDate = _data.date_end
      ? moment(_data.date_end).format("YYYY-MM-DD")
      : null;

    let filter = {};

    if (userType) {
      if (userType === 1) {
        userType = "writer";
      } else if (userType === 2) {
        userType = "artist";
      } else if (userType === 3) {
        userType = "engineer";
      } else if (userType === 4) {
        userType = "producer";
      } else {
        userType = "all";
      }

      filter = {
        name: name,
        email: email,
        user_type: userType,
      };
    } else {
      filter = {
        name: name,
        email: email,
      };
    }

    if (startDate && endDate) {
      filter = {
        ...filter,
        date_start: startDate,
        date_end: endDate,
      };
    } else if (startDate) {
      filter = {
        ...filter,
        date_start: startDate,
      };
    } else if (endDate) {
      filter = {
        ...filter,
        date_end: endDate,
      };
    }

    getData(1, pageSize, removeKeysWhenValueIsNull(filter));
  };

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

    // (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);
      })();
    }
  }, []);

  console.log("djjdj");

  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 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">
            Employees
          </h4>
          <AddButton link={`/${authState.role}/add-employee`} />
        </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-end gap-3">
                {/* Name Input */}
                <div className="flex w-1/3 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 font-medium text-white 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>

                {/* Email Input */}
                <div className="flex w-1/3 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-full rounded border-[1.5px] border-form-strokedark bg-form-input px-3 py-2 text-sm font-medium text-white 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>

                {/* User Type Select */}
                <div className="flex w-1/3 flex-col">
                  <label className="mb-1.5 text-sm font-medium text-white">
                    User Type
                  </label>
                  <CustomSelect2
                    label="User Type"
                    register={register}
                    name="user_type"
                    className="h-[36px]"
                  >
                    {userTypes?.map((elem) => {
                      return <option value={elem?.id}>{elem?.name}</option>;
                    })}
                  </CustomSelect2>
                </div>

                {/* Date Range Picker */}
                <div className="mt-3 w-2/3">
                  <div className="flex items-center gap-[22px]">
                    <label className="mb-1.5 w-[48.5%] text-sm font-medium text-white">
                      Start Date
                    </label>
                    <label className="mb-1.5 w-[46%] text-sm font-medium text-white">
                      End Date
                    </label>
                  </div>
                  <DateRangePicker
                    isOutsideRange={() => false}
                    endDateArialLabel="Date End"
                    startDateArialLabel="Date Start"
                    endDatePlaceholderText="Date End"
                    startDatePlaceholderText="Date Start"
                    displayFormat="MM-DD-YYYY"
                    onFocusChange={(focusedInput) =>
                      setFocusedInput(focusedInput)
                    }
                    focusedInput={focusedInput}
                    onDatesChange={({ startDate, endDate }) => {
                      setValue("date_start", startDate);
                      setValue("date_end", endDate);
                    }}
                    startDate={dateStart ? moment(dateStart) : ""}
                    endDateId="mix_date_end"
                    endDate={dateEnd ? moment(dateEnd) : ""}
                    startDateId="mix_date_start"
                    customInputIcon={null}
                    noBorder={true}
                  />
                </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}
                      className={`whitespace-nowrap px-3 py-3 text-left text-xs font-medium uppercase tracking-wider text-bodydark1 ${
                        column.accessor === "name" ? "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}
                      onClick={() => {
                        navigate(`/${authState.role}/view-employee/${row.id}`, {
                          state: row,
                        });
                      }}
                      className="border-b border-strokedark hover:bg-primary/5"
                    >
                      {columns.map((cell, index) => (
                        <td
                          key={index}
                          className={`whitespace-nowrap px-3 py-4  ${
                            cell.accessor === "name"
                              ? "text-bodydark1 xl:pl-6 2xl:pl-9"
                              : "text-bodydark"
                          }`}
                        >
                          {renderCellContent(cell, row)}
                        </td>
                      ))}
                    </tr>
                  ))}
                </tbody>
              ) : loading && currentTableData.length === 0 ? (
                <tbody>
                  <tr></tr>
                  <tr>
                    <td colSpan={columns.length} className="p-4 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 Employees...
                      </span>
                    </td>
                  </tr>
                  <tr></tr>
                  <tr></tr>
                  <tr></tr>
                  <tr></tr>
                  <tr></tr>
                </tbody>
              ) : !loading && 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>
              ) : (
                loading && (
                  <tbody>
                    <tr>
                      <td colSpan={columns.length} className="text-center">
                        <span className="trans relative 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 Employees...
                        </span>
                      </td>
                    </tr>
                    <tr></tr>
                    <tr></tr>
                    <tr></tr>
                    <tr></tr>
                    <tr></tr>
                  </tbody>
                )
              )}
            </table>
          </div>
        </div>

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

// Helper function to render cell content
const renderCellContent = (cell, row) => {
  if (cell.accessor.includes("image")) {
    return (
      <img
        crossOrigin="anonymous"
        src={row[cell.accessor]}
        className="h-[100px] w-[150px]"
        alt="preview"
      />
    );
  }

  if (
    ["pdf", "doc", "file", "video"].some((type) => cell.accessor.includes(type))
  ) {
    return (
      <a
        className="text-blue-500"
        target="_blank"
        href={row[cell.accessor]}
        rel="noreferrer"
      >
        View
      </a>
    );
  }

  if (
    [
      "writer_cost",
      "artist_cost",
      "engineer_cost",
      "producer_cost",
      "total_earnings",
    ].includes(cell.accessor)
  ) {
    return row[cell.accessor] ? `$${row[cell.accessor]}` : "";
  }

  if (cell.accessor === "w_nine") {
    return (
      <a
        className="text-blue-500 underline"
        target="_blank"
        href={row[cell.accessor]}
        rel="noreferrer"
      >
        View
      </a>
    );
  }

  if (cell.mappingExist) {
    return cell.mappings[row[cell.accessor]];
  }

  return row[cell.accessor];
};

export default ListEmployeePage;
