import { yupResolver } from "@hookform/resolvers/yup";
import Spinner from "Components/Spinner";
import moment from "moment";
import React from "react";
import { SingleDatePicker } from "react-dates";
import "react-dates/initialize";
import "react-dates/lib/css/_datepicker.css";
import { useForm } from "react-hook-form";
import { useNavigate } from "react-router-dom";
import { retrieveAllEmployeeAPI } from "Src/services/employeeService";
import * as yup from "yup";
import { AuthContext, tokenExpireError } from "../../authContext";
import PaginationBar from "../../components/PaginationBar";
import { getNonNullValue, removeKeysWhenValueIsNull } from "../../utils/utils";
import AddButton from "../components/AddButton";
import { GlobalContext } from "../globalContext";
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: "Producer",
    accessor: "member_name",
    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: "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 ManagerListEmployeePage = () => {
  const { dispatch, state: authState } = React.useContext(AuthContext);
  const { dispatch: globalDispatch } = React.useContext(GlobalContext);
  const [focusedInput, setFocusedInput] = React.useState({
    date_start: null,
    date_end: null,
  });
  const [dates, setDates] = React.useState({
    date_start: null,
    date_end: null,
  });

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

  // 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({
    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,
    reset,
    setValue,

    watch,
    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 () {
      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 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);
      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("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);
      })();
    }
  }, []);

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

  return (
    <>
      <form
        className="mb-10 rounded border border-gray-500 bg-gray-800 p-5 shadow"
        onSubmit={handleSubmit(onSubmit)}
      >
        <h4 className="text-2xl font-medium text-white">Employee Search</h4>
        <div className="filter-form-holder mt-4 flex flex-wrap">
          <div className="mb-4 w-full pl-2 pr-2 md:w-1/3">
            <label
              className="mb-2 block text-sm font-bold text-gray-100"
              htmlFor="name"
            >
              Name
            </label>
            <input
              placeholder="Name"
              {...register("name")}
              className={`focus:shadow-outline w-full appearance-none rounded border px-3 py-2 leading-tight text-gray-700 shadow focus:outline-none ${
                errors.name?.message ? "border-red-500" : ""
              }`}
            />
            <p className="text-xs italic text-red-500">
              {errors.name?.message}
            </p>
          </div>

          <div className="mb-4 w-full pl-2 pr-2 md:w-1/3">
            <label
              className="mb-2 block text-sm font-bold text-gray-100"
              htmlFor="email"
            >
              Email
            </label>
            <input
              placeholder="Email"
              {...register("email")}
              className={`focus:shadow-outline w-full appearance-none rounded border px-3 py-2 leading-tight text-gray-700 shadow focus:outline-none ${
                errors.email?.message ? "border-red-500" : ""
              }`}
            />
            <p className="text-xs italic text-red-500">
              {errors.email?.message}
            </p>
          </div>

          <div className="mb-4 w-full pl-2 pr-2 md:w-1/3">
            <label
              className="mb-2 block text-sm font-bold text-gray-100"
              htmlFor="status"
            >
              User Type
            </label>
            <CustomSelect2
              register={register}
              name="user_type"
              label="User Type"
              className={`focus:shadow-outline w-full appearance-none rounded border px-3 py-2 leading-tight text-gray-700 shadow focus:outline-none ${
                errors.user_type?.message ? "border-red-500" : ""
              }`}
            >
              <option value="">--Select--</option>
              {userTypes.map((item, index) => (
                <option key={index} value={item.id}>
                  {item.name}
                </option>
              ))}
            </CustomSelect2>
          </div>

          <div className="mb-4 w-full pl-2 pr-2 md:w-1/3">
            <div className="mb-1 flex w-[398px] gap-[100px] text-[12px] text-white">
              <h3 className="text-[14px] text-white">Date Start</h3>
              <h3 className="text-[14px] text-white">Date End</h3>
            </div>
            <div className="flex gap-4">
              <SingleDatePicker
                id="date_start"
                date={dates.date_start ? moment(dates.date_start) : null}
                onDateChange={(date) => {
                  setDates((prev) => ({ ...prev, date_start: date }));
                  setValue(
                    "date_start",
                    date ? date.format("YYYY-MM-DD") : null
                  );
                }}
                focused={focusedInput.date_start}
                onFocusChange={({ focused }) =>
                  setFocusedInput((prev) => ({ ...prev, date_start: focused }))
                }
                numberOfMonths={1}
                isOutsideRange={() => false}
                displayFormat="MM-DD-YYYY"
                placeholder="Select Start Date"
                readOnly={true}
                customInputIcon={null}
                noBorder={true}
                block
              />
              <SingleDatePicker
                id="date_end"
                date={dates.date_end ? moment(dates.date_end) : null}
                onDateChange={(date) => {
                  setDates((prev) => ({ ...prev, date_end: date }));
                  setValue("date_end", date ? date.format("YYYY-MM-DD") : null);
                }}
                focused={focusedInput.date_end}
                onFocusChange={({ focused }) =>
                  setFocusedInput((prev) => ({ ...prev, date_end: focused }))
                }
                numberOfMonths={1}
                isOutsideRange={() => false}
                displayFormat="MM-DD-YYYY"
                placeholder="Select End Date"
                readOnly={true}
                customInputIcon={null}
                noBorder={true}
                block
              />
            </div>
          </div>

          {/* <div className="pr-2 pl-2 mb-4 w-full md:w-1/3">
            <label
              className="block mb-2 text-sm font-bold text-gray-100"
              htmlFor="date_start"
            >
              Start Date
            </label>
            <input
              type="date"
              placeholder="Start Date"
              {...register("date_start")}
              className={`focus:shadow-outline w-full appearance-none rounded border px-3 py-2 leading-tight text-gray-700 shadow focus:outline-none ${
                errors.date_start?.message ? "border-red-500" : ""
              }`}
            />
            <p className="text-xs italic text-red-500">
              {errors.date_start?.message}
            </p>
          </div> */}

          {/* <div className="pr-2 pl-2 mb-4 w-full md:w-1/3">
            <label
              className="block mb-2 text-sm font-bold text-gray-100"
              htmlFor="date_end"
            >
              End Date
            </label>
            <input
              type="date"
              placeholder="Start Date"
              {...register("date_end")}
              className={`focus:shadow-outline w-full appearance-none rounded border px-3 py-2 leading-tight text-gray-700 shadow focus:outline-none ${
                errors.date_end?.message ? "border-red-500" : ""
              }`}
            />
            <p className="text-xs italic text-red-500">
              {errors.date_end?.message}
            </p>
          </div> */}
        </div>
        <button
          type="submit"
          className="focus:shadow-outline ml-2 inline rounded bg-primary px-4 py-2 font-bold text-white hover:bg-primary/90 focus:outline-none"
        >
          Search
        </button>

        <button
          onClick={() => {
            resetForm();
          }}
          type="button"
          className="focus:shadow-outline ml-2 inline rounded bg-red-500 px-4 py-2 font-bold text-white hover:bg-red-700 focus:outline-none"
        >
          Clear
        </button>
      </form>

      <div className="overflow-x-auto rounded border border-gray-500 bg-gray-800 p-5 shadow">
        <div className="mb-3 flex w-full flex-row justify-between">
          <h4 className="text-2xl font-medium text-white">Employees </h4>
          <AddButton link={`/${authState.role}/add-employee`} />
        </div>
        <div className="overflow-x-auto rounded-md border-b border-gray-200 shadow">
          <table className="min-w-full divide-y divide-gray-200">
            <thead className="bg-gray-900">
              <tr>
                {columns.map((column, i) => (
                  <th
                    key={i}
                    scope="col"
                    className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-white"
                  >
                    {column.header}
                    <span>
                      {column.isSorted
                        ? column.isSortedDesc
                          ? " ▼"
                          : " ▲"
                        : ""}
                    </span>
                  </th>
                ))}
              </tr>
            </thead>
            <tbody className="cursor-pointer divide-y divide-gray-100 bg-neutral-950 text-white">
              {loading && <Spinner />}
              {currentTableData.map((row, i) => {
                return (
                  <tr
                    key={i}
                    className="hover:bg-gray-800"
                    // onClick={() => {
                    //   navigate(`/${authState.role}/view-employee/` + row.id, {
                    //     state: row,
                    //   });
                    // }}
                  >
                    {columns.map((cell, index) => {
                      if (cell.accessor.indexOf("image") > -1) {
                        return (
                          <td
                            key={index}
                            className="whitespace-nowrap px-6 py-4"
                          >
                            <img
                              crossOrigin="anonymous"
                              src={row[cell.accessor]}
                              className="h-[100px] w-[150px]"
                              alt="test"
                            />
                          </td>
                        );
                      }
                      if (
                        cell.accessor.indexOf("pdf") > -1 ||
                        cell.accessor.indexOf("doc") > -1 ||
                        cell.accessor.indexOf("file") > -1 ||
                        cell.accessor.indexOf("video") > -1
                      ) {
                        return (
                          <td
                            key={index}
                            className="whitespace-nowrap px-6 py-4"
                          >
                            <a
                              className="text-blue-500"
                              target="_blank"
                              href={row[cell.accessor]}
                              rel="noreferrer"
                            >
                              {" "}
                              View
                            </a>
                          </td>
                        );
                      }
                      if (cell.accessor === "writer_cost") {
                        return (
                          <td
                            key={index}
                            className="whitespace-nowrap px-6 py-4"
                          >
                            {row[cell.accessor] ? `$${row[cell.accessor]}` : ""}
                          </td>
                        );
                      }
                      if (cell.accessor === "artist_cost") {
                        return (
                          <td
                            key={index}
                            className="whitespace-nowrap px-6 py-4"
                          >
                            {row[cell.accessor] ? `$${row[cell.accessor]}` : ""}
                          </td>
                        );
                      }
                      if (cell.accessor === "engineer_cost") {
                        return (
                          <td
                            key={index}
                            className="whitespace-nowrap px-6 py-4"
                          >
                            {row[cell.accessor] ? `$${row[cell.accessor]}` : ""}
                          </td>
                        );
                      }
                      if (cell.accessor === "producer_cost") {
                        return (
                          <td
                            key={index}
                            className="whitespace-nowrap px-6 py-4"
                          >
                            {row[cell.accessor] ? `$${row[cell.accessor]}` : ""}
                          </td>
                        );
                      }
                      if (cell.accessor === "total_earnings") {
                        return (
                          <td
                            key={index}
                            className="whitespace-nowrap px-6 py-4"
                          >
                            {row[cell.accessor] ? `$${row[cell.accessor]}` : ""}
                          </td>
                        );
                      }
                      if (cell.accessor === "w_nine") {
                        return (
                          <td
                            key={index}
                            className="whitespace-nowrap px-6 py-4"
                          >
                            <a
                              className="text-blue-500 underline"
                              target="_blank"
                              href={row[cell.accessor]}
                              rel="noreferrer"
                            >
                              View
                            </a>
                          </td>
                        );
                      }
                      if (cell.accessor === "member_name") {
                        return (
                          <td
                            key={index}
                            className="whitespace-nowrap px-6 py-4"
                          >
                            {row.member_name}
                          </td>
                        );
                      }
                      if (cell.mappingExist) {
                        return (
                          <td
                            key={index}
                            className="whitespace-nowrap px-6 py-4"
                          >
                            {cell.mappings[row[cell.accessor]]}
                          </td>
                        );
                      }
                      return (
                        <td key={index} className="whitespace-nowrap px-6 py-4">
                          {row[cell.accessor]}
                        </td>
                      );
                    })}
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </div>
      <PaginationBar
        currentPage={currentPage}
        pageCount={pageCount}
        pageSize={pageSize}
        canPreviousPage={canPreviousPage}
        canNextPage={canNextPage}
        updatePageSize={updatePageSize}
        previousPage={previousPage}
        nextPage={nextPage}
      />
    </>
  );
};

export default ManagerListEmployeePage;
