import React, { useState } from "react";
import { AuthContext, tokenExpireError } from "Src/authContext";
import { useForm } from "react-hook-form";
import { useNavigate } from "react-router-dom";
import { yupResolver } from "@hookform/resolvers/yup";
import * as yup from "yup";
import moment from "moment";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import ClipLoader from "react-spinners/ClipLoader";

import { GlobalContext, showToast } from "Src/globalContext";
import {
  getNonNullValue,
  calculateManagementDiscount,
  calculateNetTotal,
  removeKeysWhenValueIsNull,
} from "Src/utils/utils";
import PaginationBar from "Src/components/PaginationBar";
import AddButton from "Src/components/AddButton";
import {
  getAllProducersAPI,
  getAllProjectsClientAPI,
  retrieveAllProjectsForClientAPI,
} from "Src/services/clientService";
import { getAllClientAPI } from "Src/services/clientService";
import { getAllMixTypeAPI } from "Src/services/mixTypeServices";
import { retrieveAllSettingsAPI } from "Src/services/settingService";
import Spinner from "Components/Spinner";
import { getUserDetailsByIdAPI } from "Src/services/userService";
import ClientProjectColumns from "Components/Client/ClientProjectColumns";
import LiveDateTime from "Components/LiveDateTime/LiveDateTime";
import { getAllMixTypeClientAPI } from "Src/services/clientProjectDetailsService";
import Select from "react-select";
import { list } from "postcss";
import { DateRangePicker } from "react-dates";
import FormMultiSelect from "Components/FormMultiSelect";

const ClientListProjectPage = () => {
  const navigate = useNavigate();
  const columns = [
    {
      header: "Mix Date",
      accessor: "mix_date",
      isSorted: false,
      isSortedDesc: false,
      mappingExist: false,
      mappings: {},
    },
    {
      header: "Program/Team",
      accessor: "program_name",
      isSorted: false,
      isSortedDesc: false,
      mappingExist: false,
      mappings: {},
    },
    {
      header: "Producer",
      accessor: "producer",
      isSorted: false,
      isSortedDesc: false,
      mappingExist: false,
      mappings: {},
    },

    {
      header: "Mix Type",
      accessor: "mix_type_name",
      isSorted: false,
      isSortedDesc: false,
      mappingExist: false,
      mappings: {},
    },
    {
      header: "Team Type",
      accessor: "team_type",
      isSorted: false,
      isSortedDesc: false,
      mappingExist: true,
      mappings: {
        1: "All Girl",
        2: "Co-ed",
        3: "TBD",
      },
    },
    {
      header: "PAYMENT STATUS",
      accessor: "payment",
      isSorted: false,
      isSortedDesc: false,
      mappingExist: false,
      mappings: {},
    },
    {
      header: "TD/ED",
      accessor: "Td&Ed",
      isSorted: false,
      isSortedDesc: false,
      mappingExist: false,
      mappings: {},
    },
    {
      header: "STATUS",
      accessor: "content_status",
      isSorted: false,
      isSortedDesc: false,
      mappingExist: false,
      mappings: {},
    },
  ];

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

  const [isLoading, setIsLoading] = React.useState(false);
  const [clients, setClients] = React.useState([]);
  const [producers, setProdcuer] = React.useState([]);

  const [mixTypes, setMixTypes] = React.useState([]);

  const [producersForSelect, setProducersForSelect] = React.useState([]);
  const [selectedProducers, setSelectedProducers] = React.useState([]);

  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);
  const [focusedInput, setFocusedInput] = React.useState(false);

  const [cachedProjectProducer, setCachedProjectProducer] = React.useState("");
  const [cachedProjectClientId, setCachedProjectClientId] = React.useState("");
  const [cachedProjectProjectTeamName, setCachedProjectProjectTeamName] =
    React.useState("");
  const [cachedProjectMixTypeId, setCachedProjectMixTypeId] =
    React.useState("");
  const [cachedProjectMixDateStart, setCachedProjectMixDateStart] =
    React.useState("");
  const [cachedProjectMixDateEnd, setCachedProjectMixDateEnd] =
    React.useState("");
  const [thisWeekSelected, setThisWeekSelected] = React.useState(false);
  const [mixTypesForSelect, setMixTypesForSelect] = React.useState([]);
  const [selectedMixTypeIds, setSelectedMixTypeIds] = React.useState([]);

  const [teamNamesForSelect, setTeamNamesForSelect] = React.useState([]);
  const [selectedTeamNames, setSelectedTeamNames] = React.useState([]);

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

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

  const [reFilter, setReFilter] = useState(false);

  React.useEffect(() => {
    let projectClientId =
      localStorage.getItem("ClientProjectClientId") &&
      JSON.parse(localStorage.getItem("ClientProjectClientId"));
    let projectTeamName =
      localStorage.getItem("ClientProjectTeamName") &&
      JSON.parse(localStorage.getItem("ClientProjectTeamName"));
    let projectMixTypeId =
      localStorage.getItem("ClientProjectMixTypeId") &&
      JSON.parse(localStorage.getItem("ClientProjectMixTypeId"));
    let projectProducers =
      localStorage.getItem("ClientProjectProducerName") &&
      JSON.parse(localStorage.getItem("ClientProjectProducerName"));

    let projectMixDateStart = localStorage.getItem("ClientProjectMixDateStart");
    let projectMixDateEnd = localStorage.getItem("ClientProjectMixDateEnd");

    setCachedProjectClientId(projectClientId);
    setCachedProjectProjectTeamName(projectTeamName);
    setCachedProjectProducer(projectProducers);
    setCachedProjectMixTypeId(projectMixTypeId);
    setCachedProjectMixDateStart(projectMixDateStart);
    setCachedProjectMixDateEnd(projectMixDateEnd);

    projectMixTypeId &&
      projectMixTypeId?.length > 0 &&
      setSelectedMixTypeIds(projectMixTypeId);

    projectTeamName &&
      projectTeamName.length > 0 &&
      setCachedProjectProjectTeamName(projectTeamName);

    projectProducers &&
      projectProducers?.length > 0 &&
      setSelectedProducers(projectProducers);

    projectTeamName &&
      projectTeamName?.length > 0 &&
      setSelectedTeamNames(projectTeamName);
  }, []);

  React.useEffect(() => {
    (async function () {
      setIsLoading(true);
      // await getData(
      //   currentPage + 1 <= pageCount ? currentPage + 1 : 0,
      //   pageSize
      // );

      let projectClientId =
        localStorage.getItem("ClientProjectClientId") &&
        JSON.parse(localStorage.getItem("ClientProjectClientId"));
      let projectTeamName =
        localStorage.getItem("ClientProjectTeamName") &&
        JSON.parse(localStorage.getItem("ClientProjectTeamName"));
      let projectProducers =
        localStorage.getItem("ClientProjectProducerName") &&
        JSON.parse(localStorage.getItem("ClientProjectProducerName"));
      let projectMixTypeId =
        localStorage.getItem("ClientProjectMixTypeId") &&
        JSON.parse(localStorage.getItem("ClientProjectMixTypeId"));
      let projectMixDateStart = localStorage.getItem(
        "ClientProjectMixDateStart"
      );
      let projectMixDateEnd = localStorage.getItem("ClientProjectMixDateEnd");

      setCachedProjectClientId(projectClientId);
      setCachedProjectProjectTeamName(projectTeamName);
      setCachedProjectMixTypeId(projectMixTypeId);
      setCachedProjectMixDateStart(projectMixDateStart);
      setCachedProjectMixDateEnd(projectMixDateEnd);
      setCachedProjectProducer(projectProducers);

      let client_ids = [];
      if (projectClientId?.length > 0) {
        projectClientId.forEach((row) => {
          client_ids.push(row.value);
        });
      }
      // let team_name = getNonNullValue(_data.team_name);
      let team_names = [];
      if (projectTeamName?.length > 0) {
        projectTeamName.forEach((row) => {
          team_names.push(row.value);
        });
      }

      let producer_names = [];
      if (projectProducers?.length > 0) {
        projectProducers.forEach((row) => {
          producer_names.push(row.label);
        });
      }

      // let mix_type_id = getNonNullValue(_data.mix_type_id);
      let mix_type_ids = [];
      if (projectMixTypeId?.length > 0) {
        projectMixTypeId.forEach((row) => {
          mix_type_ids.push(row.value);
        });
      }
      let mix_date_start = getNonNullValue(cachedProjectMixDateStart);
      let mix_date_end = getNonNullValue(cachedProjectMixDateStart);
      mix_date_start = mix_date_start
        ? moment(mix_date_start).format("YYYY-MM-DD")
        : null;
      mix_date_end = mix_date_end
        ? moment(mix_date_end).format("YYYY-MM-DD")
        : null;

      if (mix_date_start && mix_date_end && mix_date_start > mix_date_end) {
        setError("mix_date_start", {
          type: "manual",
          message: "Mix Date Start must be less than Mix Date End",
        });
        setIsLoading(false);
        return;
      }

      if (
        producer_names?.length > 0 ||
        client_ids?.length > 0 ||
        team_names?.length > 0 ||
        mix_type_ids?.length > 0 ||
        projectMixDateStart ||
        projectMixDateEnd
      ) {
        let filter = {
          client_ids: client_ids ?? null,
          team_names: team_names ?? null,
          producer_name: producer_names ?? null,
          mix_type_ids: mix_type_ids ?? null,
          mix_date_start: projectMixDateStart,
          mix_date_end: projectMixDateEnd,
        };

        await getData(
          1,
          pageSizeFromLocalStorage ? pageSizeFromLocalStorage : pageSize,
          removeKeysWhenValueIsNull(filter)
        );
      } else {
        await getData(
          1,
          pageSizeFromLocalStorage ? pageSizeFromLocalStorage : pageSize
        );
      }
      setIsLoading(false);
    })();
  }, [reFilter]);

  const getAllMixTypes = async () => {
    try {
      const result = await getAllMixTypeClientAPI();
      if (!result.error) {
        if (result.list.length > 0) {
          let forSelect = [];
          if (result.list.length > 0) {
            result.list.map((row, i) => {
              forSelect.push({
                value: row.id,
                label: row.name,
              });
            });
          }
          setMixTypesForSelect(forSelect);
        }
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  const getAllProducers = async () => {
    try {
      const result = await getAllProducersAPI();

      if (!result.error) {
        if (result.list.length > 0) {
          let forSelect = [];
          if (result.list.length > 0) {
            result.list.map((row, i) => {
              forSelect.push({
                value: row.id,
                label: row.name,
              });
            });
          }
          setProducersForSelect(forSelect);
        }
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  const schema = yup.object({
    client_id: yup.string(),
    producer_name: yup.string(),
    team_name: yup.string(),
    mix_type_id: yup.string(),
    mix_date_start: yup.string(),
    mix_date_end: yup.string(),
  });

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

  function updatePageSize(limit) {
    (async function () {
      setIsLoading(true);
      setPageSize(limit);
      let UserClientId = localStorage.getItem("userClientId");

      let projectProducerName =
        localStorage.getItem("ClientProjectProducerName") &&
        JSON.parse(localStorage.getItem("ClientProjectProducerName"));
      setCachedProjectProducer(projectProducerName);

      let projectTeamName =
        localStorage.getItem("ClientProjectTeamName") &&
        JSON.parse(localStorage.getItem("ClientProjectTeamName"));
      let projectMixTypeId =
        localStorage.getItem("ClientProjectMixTypeId") &&
        JSON.parse(localStorage.getItem("ClientProjectMixTypeId"));
      let projectMixDateStart = localStorage.getItem(
        "ClientProjectMixDateStart"
      );
      let projectMixDateEnd = localStorage.getItem("ClientProjectMixDateEnd");

      setCachedProjectProjectTeamName(projectTeamName);
      setCachedProjectMixTypeId(projectMixTypeId);
      setCachedProjectMixDateStart(projectMixDateStart);
      setCachedProjectMixDateEnd(projectMixDateEnd);
      setCachedProjectProducer(projectProducerName);

      // let team_name = getNonNullValue(_data.team_name);
      let team_names = [];
      if (projectTeamName?.length > 0) {
        projectTeamName.forEach((row) => {
          team_names.push(row.value);
        });
      }

      let producer_names = [];

      if (projectProducerName?.length > 0) {
        projectProducerName.forEach((row) => {
          producer_names.push(row.value);
        });
      }

      // let mix_type_id = getNonNullValue(_data.mix_type_id);
      let mix_type_ids = [];
      if (projectMixTypeId?.length > 0) {
        projectMixTypeId.forEach((row) => {
          mix_type_ids.push(row.value);
        });
      }
      let mix_date_start = getNonNullValue(cachedProjectMixDateStart);
      let mix_date_end = getNonNullValue(cachedProjectMixDateStart);
      mix_date_start = mix_date_start
        ? moment(mix_date_start).format("YYYY-MM-DD")
        : null;
      mix_date_end = mix_date_end
        ? moment(mix_date_end).format("YYYY-MM-DD")
        : null;

      if (mix_date_start && mix_date_end && mix_date_start > mix_date_end) {
        setError("mix_date_start", {
          type: "manual",
          message: "Mix Date Start must be less than Mix Date End",
        });
        setIsLoading(false);
        return;
      }

      if (
        producer_names?.length > 0 ||
        team_names?.length > 0 ||
        projectMixTypeId?.length > 0 ||
        projectMixDateStart ||
        projectMixDateEnd
      ) {
        let filter = {
          client_id: UserClientId ? Number(UserClientId) : null,
          producer_name: producer_names ?? null,
          team_name: team_names ?? null,
          mix_type_id: mix_type_ids ?? null,
          mix_date_start: projectMixDateStart,
          mix_date_end: projectMixDateEnd,
        };

        if (!pageSizeFromLocalStorage) {
          (async function () {
            await getData(1, limit, filter);
          })();
        } else {
          (async function () {
            await getData(1, limit, filter);
          })();
        }
      } else {
        if (!pageSizeFromLocalStorage) {
          (async function () {
            await getData(1, limit);
          })();
        } else {
          (async function () {
            await getData(1, limit);
          })();
        }
      }
      setIsLoading(false);
    })();
    localStorage.setItem("clientProjectPageSize", limit);
  }

  function previousPage() {
    (async function () {
      setIsLoading(true);

      let UserClientId = localStorage.getItem("userClientId");

      let projectProducerName =
        localStorage.getItem("ClientProjectProducerName") &&
        JSON.parse(localStorage.getItem("ClientProjectProducerName"));
      setCachedProjectProducer(projectProducerName);
      // await getData(currentPage - 1 > 0 ? currentPage - 1 : 0, pageSize);

      JSON.parse(localStorage.getItem("ClientProjectClientId"));
      let projectTeamName =
        localStorage.getItem("ClientProjectTeamName") &&
        JSON.parse(localStorage.getItem("ClientProjectTeamName"));
      let projectMixTypeId =
        localStorage.getItem("ClientProjectMixTypeId") &&
        JSON.parse(localStorage.getItem("ClientProjectMixTypeId"));
      let projectMixDateStart = localStorage.getItem(
        "ClientProjectMixDateStart"
      );
      let projectMixDateEnd = localStorage.getItem("ClientProjectMixDateEnd");

      setCachedProjectProjectTeamName(projectTeamName);
      setCachedProjectMixTypeId(projectMixTypeId);
      setCachedProjectMixDateStart(projectMixDateStart);
      setCachedProjectMixDateEnd(projectMixDateEnd);
      setCachedProjectProducer(projectProducerName);

      // let team_name = getNonNullValue(_data.team_name);
      let team_names = [];
      if (projectTeamName?.length > 0) {
        projectTeamName.forEach((row) => {
          team_names.push(row.value);
        });
      }

      let producer_names = [];
      if (projectProducerName?.length > 0) {
        projectProducerName.forEach((row) => {
          producer_names.push(row.value);
        });
      }

      // let mix_type_id = getNonNullValue(_data.mix_type_id);
      let mix_type_ids = [];
      if (projectMixTypeId?.length > 0) {
        projectMixTypeId.forEach((row) => {
          mix_type_ids.push(row.value);
        });
      }
      let mix_date_start = getNonNullValue(cachedProjectMixDateStart);
      let mix_date_end = getNonNullValue(cachedProjectMixDateStart);
      mix_date_start = mix_date_start
        ? moment(mix_date_start).format("YYYY-MM-DD")
        : null;
      mix_date_end = mix_date_end
        ? moment(mix_date_end).format("YYYY-MM-DD")
        : null;

      if (mix_date_start && mix_date_end && mix_date_start > mix_date_end) {
        setError("mix_date_start", {
          type: "manual",
          message: "Mix Date Start must be less than Mix Date End",
        });
        setIsLoading(false);
        return;
      }

      if (
        producer_names?.length > 0 ||
        team_names?.length > 0 ||
        projectMixTypeId?.length > 0 ||
        projectMixDateStart ||
        projectMixDateEnd
      ) {
        let filter = {
          client_id: UserClientId ? Number(UserClientId) : null,
          producer_name: producer_names ?? null,
          team_name: team_names ?? null,
          mix_type_id: mix_type_ids ?? null,
          mix_date_start: projectMixDateStart,
          mix_date_end: projectMixDateEnd,
        };

        await getData(
          currentPage - 1,
          pageSizeFromLocalStorage ? pageSizeFromLocalStorage : pageSize,
          filter
        );
      } else {
        await getData(
          currentPage - 1,
          pageSizeFromLocalStorage ? pageSizeFromLocalStorage : pageSize
        );
      }
      setIsLoading(false);
    })();
  }

  function callDataAgain(page) {
    (async function () {
      setIsLoading(true);

      let UserClientId = localStorage.getItem("userClientId");

      let projectProducerName =
        localStorage.getItem("ClientProjectProducerName") &&
        JSON.parse(localStorage.getItem("ClientProjectProducerName"));
      setCachedProjectProducer(projectProducerName);
      // await getData(currentPage - 1 > 0 ? currentPage - 1 : 0, pageSize);

      JSON.parse(localStorage.getItem("ClientProjectClientId"));
      let projectTeamName =
        localStorage.getItem("ClientProjectTeamName") &&
        JSON.parse(localStorage.getItem("ClientProjectTeamName"));
      let projectMixTypeId =
        localStorage.getItem("ClientProjectMixTypeId") &&
        JSON.parse(localStorage.getItem("ClientProjectMixTypeId"));
      let projectMixDateStart = localStorage.getItem(
        "ClientProjectMixDateStart"
      );
      let projectMixDateEnd = localStorage.getItem("ClientProjectMixDateEnd");

      setCachedProjectProjectTeamName(projectTeamName);
      setCachedProjectMixTypeId(projectMixTypeId);
      setCachedProjectMixDateStart(projectMixDateStart);
      setCachedProjectMixDateEnd(projectMixDateEnd);
      setCachedProjectProducer(projectProducerName);

      // let team_name = getNonNullValue(_data.team_name);
      let team_names = [];
      if (projectTeamName?.length > 0) {
        projectTeamName.forEach((row) => {
          team_names.push(row.value);
        });
      }

      let producer_names = [];
      if (projectProducerName?.length > 0) {
        projectProducerName.forEach((row) => {
          producer_names.push(row.value);
        });
      }

      // let mix_type_id = getNonNullValue(_data.mix_type_id);
      let mix_type_ids = [];
      if (projectMixTypeId?.length > 0) {
        projectMixTypeId.forEach((row) => {
          mix_type_ids.push(row.value);
        });
      }
      let mix_date_start = getNonNullValue(cachedProjectMixDateStart);
      let mix_date_end = getNonNullValue(cachedProjectMixDateStart);
      mix_date_start = mix_date_start
        ? moment(mix_date_start).format("YYYY-MM-DD")
        : null;
      mix_date_end = mix_date_end
        ? moment(mix_date_end).format("YYYY-MM-DD")
        : null;

      if (mix_date_start && mix_date_end && mix_date_start > mix_date_end) {
        setError("mix_date_start", {
          type: "manual",
          message: "Mix Date Start must be less than Mix Date End",
        });
        setIsLoading(false);
        return;
      }

      if (
        producer_names?.length > 0 ||
        team_names?.length > 0 ||
        projectMixTypeId?.length > 0 ||
        projectMixDateStart ||
        projectMixDateEnd
      ) {
        let filter = {
          client_id: UserClientId ? Number(UserClientId) : null,
          producer_name: producer_names ?? null,
          team_name: team_names ?? null,
          mix_type_id: mix_type_ids ?? null,
          mix_date_start: projectMixDateStart,
          mix_date_end: projectMixDateEnd,
        };

        await getData(
          page,
          pageSizeFromLocalStorage ? pageSizeFromLocalStorage : pageSize,
          filter
        );
      } else {
        await getData(
          page,
          pageSizeFromLocalStorage ? pageSizeFromLocalStorage : pageSize
        );
      }
      setIsLoading(false);
    })();
  }

  function nextPage() {
    (async function () {
      setIsLoading(true);
      // await getData(
      //   currentPage + 1 <= pageCount ? currentPage + 1 : 0,
      //   pageSize
      // )

      let UserClientId = localStorage.getItem("userClientId");

      let projectProducerName =
        localStorage.getItem("ClientProjectProducerName") &&
        JSON.parse(localStorage.getItem("ClientProjectProducerName"));
      setCachedProjectProducer(projectProducerName);
      // await getData(currentPage - 1 > 0 ? currentPage - 1 : 0, pageSize);

      JSON.parse(localStorage.getItem("ClientProjectClientId"));
      let projectTeamName =
        localStorage.getItem("ClientProjectTeamName") &&
        JSON.parse(localStorage.getItem("ClientProjectTeamName"));
      let projectMixTypeId =
        localStorage.getItem("ClientProjectMixTypeId") &&
        JSON.parse(localStorage.getItem("ClientProjectMixTypeId"));
      let projectMixDateStart = localStorage.getItem(
        "ClientProjectMixDateStart"
      );
      let projectMixDateEnd = localStorage.getItem("ClientProjectMixDateEnd");

      setCachedProjectProjectTeamName(projectTeamName);
      setCachedProjectMixTypeId(projectMixTypeId);
      setCachedProjectMixDateStart(projectMixDateStart);
      setCachedProjectMixDateEnd(projectMixDateEnd);
      setCachedProjectProducer(projectProducerName);

      // let team_name = getNonNullValue(_data.team_name);
      let team_names = [];
      if (projectTeamName?.length > 0) {
        projectTeamName.forEach((row) => {
          team_names.push(row.value);
        });
      }

      let producer_names = [];
      if (projectProducerName?.length > 0) {
        projectProducerName.forEach((row) => {
          producer_names.push(row.label);
        });
      }

      // let mix_type_id = getNonNullValue(_data.mix_type_id);
      let mix_type_ids = [];
      if (projectMixTypeId?.length > 0) {
        projectMixTypeId.forEach((row) => {
          mix_type_ids.push(row.value);
        });
      }
      let mix_date_start = getNonNullValue(cachedProjectMixDateStart);
      let mix_date_end = getNonNullValue(cachedProjectMixDateStart);
      mix_date_start = mix_date_start
        ? moment(mix_date_start).format("YYYY-MM-DD")
        : null;
      mix_date_end = mix_date_end
        ? moment(mix_date_end).format("YYYY-MM-DD")
        : null;

      if (mix_date_start && mix_date_end && mix_date_start > mix_date_end) {
        setError("mix_date_start", {
          type: "manual",
          message: "Mix Date Start must be less than Mix Date End",
        });
        setIsLoading(false);
        return;
      }

      if (
        team_names?.length > 0 ||
        projectMixTypeId?.length > 0 ||
        projectMixDateStart ||
        projectMixDateEnd
      ) {
        let filter = {
          client_id: UserClientId ? Number(UserClientId) : null,
          producer_name: producer_names ?? null,
          team_name: team_names ?? null,
          mix_type_id: mix_type_ids ?? null,
          mix_date_start: projectMixDateStart,
          mix_date_end: projectMixDateEnd,
        };

        await getData(
          currentPage + 1,
          pageSizeFromLocalStorage ? pageSizeFromLocalStorage : pageSize,
          filter
        );
      } else {
        await getData(
          currentPage + 1,
          pageSizeFromLocalStorage ? pageSizeFromLocalStorage : pageSize
        );
      }
      setIsLoading(false);
    })();
  }

  async function getData(pageNum, limitNum, filter) {
    let UserClientId = localStorage.getItem("userClientId");
    try {
      setIsLoading(true);
      let localFilter = {
        ...filter,

        is_impersonate: false,
        client_id: UserClientId ? Number(UserClientId) : null,
      };
      const result = await retrieveAllProjectsForClientAPI(
        pageNum,
        limitNum,
        localFilter
      );
      const { list, total, limit, num_pages, page } = result;
      const paidList = list.filter(
        (elem) =>
          elem?.payment_status > 0 &&
          elem?.payment_status !== 5 &&
          elem?.subscription > 1
      );

      setCurrentTableData(paidList);
      // setPageSize(limit);
      setPageCount(num_pages);
      setPage(page);
      setDataTotal(total);
      setCanPreviousPage(page > 1);
      setCanNextPage(page + 1 <= num_pages);
      setIsLoading(false);
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  }

  const resetForm = async () => {
    reset();
    setIsLoading(true);

    localStorage.setItem("ClientProjectTeamName", "");
    localStorage.setItem("ClientProjectMixTypeId", "");
    localStorage.setItem("ClientProjectMixDateStart", "");
    localStorage.setItem("ClientProjectMixDateEnd", "");
    localStorage.setItem("clientProjectPageSize", "");
    localStorage.setItem("ClientProjectProducerName", "");

    setCachedProjectProducer("");
    setSelectedMixTypeIds([]);
    setSelectedTeamNames([]);
    setSelectedProducers([]);
    setCachedProjectProducer("");
    setCachedProjectProjectTeamName("");
    setCachedProjectMixTypeId("");
    setCachedProjectMixDateStart("");
    setCachedProjectMixDateEnd("");
    setPageSize(10);

    await getData(1, pageSize);
    setIsLoading(false);
  };

  const onSubmit = async (_data) => {
    try {
      setIsLoading(true);

      // let team_name = getNonNullValue(_data.team_name);
      let team_names = [];
      if (selectedTeamNames.length > 0) {
        selectedTeamNames.forEach((row) => {
          team_names.push(row.value);
        });
      }

      let producer_names = [];
      if (selectedProducers?.length > 0) {
        selectedProducers.forEach((row) => {
          producer_names.push(row.label);
        });
      }
      // let mix_type_id = getNonNullValue(_data.mix_type_id);
      let mix_type_ids = [];
      if (selectedMixTypeIds.length > 0) {
        selectedMixTypeIds.forEach((row) => {
          mix_type_ids.push(row.value);
        });
      }
      let mix_date_start = getNonNullValue(_data.mix_date_start);
      let mix_date_end = getNonNullValue(_data.mix_date_end);
      mix_date_start = mix_date_start
        ? moment(mix_date_start).format("YYYY-MM-DD")
        : null;
      mix_date_end = mix_date_end
        ? moment(mix_date_end).format("YYYY-MM-DD")
        : null;

      if (mix_date_start && mix_date_end && mix_date_start > mix_date_end) {
        setError("mix_date_start", {
          type: "manual",
          message: "Mix Date Start must be less than Mix Date End",
        });
        setIsLoading(false);
        return;
      }

      let filter = {
        producer_name: producer_names ?? null,
        team_names: team_names ?? null,
        mix_type_ids: mix_type_ids ?? null,
        mix_date_start: mix_date_start,
        mix_date_end: mix_date_end,
      };

      //

      if (
        !producer_names.length > 0 &&
        !team_names?.length &&
        !mix_type_ids?.length > 0 &&
        !mix_date_start &&
        !mix_date_end
      ) {
        setIsLoading(false);
        return;
      }

      // localStorage.setItem('ClientProjectClientId', client_id ?? '');
      // localStorage.setItem('ClientProjectProducerName', producer_name ?? '');
      // localStorage.setItem('ClientProjectTeamName', team_name ?? '');
      // localStorage.setItem('ClientProjectMixTypeId', mix_type_id ?? '');
      localStorage.setItem("ClientProjectMixDateStart", mix_date_start ?? "");
      localStorage.setItem("ClientProjectMixDateEnd", mix_date_end ?? "");

      // await getData(1, pageSize, removeKeysWhenValueIsNull(filter));

      if (!pageSizeFromLocalStorage) {
        (async function () {
          await getData(1, pageSize, removeKeysWhenValueIsNull(filter));
        })();
      } else {
        (async function () {
          await getData(
            1,
            pageSizeFromLocalStorage,
            removeKeysWhenValueIsNull(filter)
          );
        })();
      }

      setIsLoading(false);
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  const getAllProjects = async () => {
    try {
      const result = await getAllProjectsClientAPI();

      if (!result.error) {
        if (result.list.length > 0) {
          let teamNames = [];
          let teamNamesForSelect = [];
          if (result.list.length > 0) {
            result.list.forEach((row) => {
              teamNames.push(row.team_name);
              teamNamesForSelect.push({
                value: row.team_name,
                label: row.team_name,
              });
            });
          }
          // keep the unique team names
          teamNames = [...new Set(teamNames)];
          // sort by alphabetical order
          teamNames.sort();
          teamNamesForSelect.sort((a, b) => {
            return a.label.localeCompare(b.label);
          });
          setTeamNamesForSelect(teamNamesForSelect);
        }
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  const handleSelectedTeamNames = (names) => {
    if (names.length === 0) {
      setSelectedTeamNames([]);
      localStorage.setItem("ClientProjectTeamName", JSON.stringify(""));
      setCachedProjectProjectTeamName([]);
    } else {
      setSelectedTeamNames(names);
      localStorage.setItem("ClientProjectTeamName", JSON.stringify(names));
      setCachedProjectProjectTeamName(names);
    }

    if (names?.length < selectedTeamNames.length) {
      setReFilter(!reFilter);
    }
  };

  const handleSelectedMixTypeIds = (ids) => {
    if (ids.length === 0) {
      setSelectedMixTypeIds([]);
      localStorage.setItem("ClientProjectMixTypeId", JSON.stringify(""));
      setCachedProjectMixTypeId([]);
    } else {
      setSelectedMixTypeIds(ids);
      localStorage.setItem("ClientProjectMixTypeId", JSON.stringify(ids));
      setCachedProjectMixTypeId(ids);
    }

    if (ids?.length < selectedMixTypeIds.length) {
      setReFilter(!reFilter);
    }
  };

  const handleThisWeekFilter = async (e) => {
    let team_names = [];
    if (selectedTeamNames.length > 0) {
      selectedTeamNames.forEach((row) => {
        team_names.push(row.value);
      });
    }

    let producer_names = [];
    if (selectedProducers?.length > 0) {
      selectedProducers.forEach((row) => {
        producer_names.push(row.label);
      });
    }
    // let mix_type_id = getNonNullValue(_data.mix_type_id);
    let mix_type_ids = [];
    if (selectedMixTypeIds.length > 0) {
      selectedMixTypeIds.forEach((row) => {
        mix_type_ids.push(row.value);
      });
    }

    if (thisWeekSelected) {
      try {
        setIsLoading(true);
        setThisWeekSelected(false);
        const startOfWeek = moment().startOf("week").format("YYYY-MM-DD");
        const endOfWeek = moment().endOf("week").format("YYYY-MM-DD");

        setCachedProjectMixDateStart("");
        setCachedProjectMixDateEnd("");

        let filter = {
          team_names: team_names ?? null,
          producer_name: producer_names ?? null,
          mix_type_ids: mix_type_ids ?? null,
        };

        // set filter to local storage
        localStorage.setItem("ClientProjectMixDateStart", "");
        localStorage.setItem("ClientProjectMixDateEnd", "");

        if (!pageSizeFromLocalStorage) {
          (async function () {
            await getData(1, pageSize, filter);
          })();
        } else {
          (async function () {
            await getData(1, pageSizeFromLocalStorage, filter);
          })();
        }

        setIsLoading(false);
      } catch (error) {
        tokenExpireError(dispatch, error.message);
      }
    } else {
      try {
        setIsLoading(true);
        setThisWeekSelected(true);
        const startOfWeek = moment().startOf("week").format("YYYY-MM-DD");
        const endOfWeek = moment().endOf("week").format("YYYY-MM-DD");

        setCachedProjectMixDateStart(startOfWeek);
        setCachedProjectMixDateEnd(endOfWeek);

        let filter = {
          team_names: team_names ?? null,
          mix_type_ids: mix_type_ids ?? null,
          mix_date_start: startOfWeek,
          producer_name: producer_names ?? null,
          mix_date_end: endOfWeek,
        };

        // set filter to local storage
        localStorage.setItem("ClientProjectMixDateStart", startOfWeek);
        localStorage.setItem("ClientProjectMixDateEnd", endOfWeek);

        if (!pageSizeFromLocalStorage) {
          (async function () {
            await getData(1, pageSize, filter);
          })();
        } else {
          (async function () {
            await getData(1, pageSizeFromLocalStorage, filter);
          })();
        }

        setIsLoading(false);
      } catch (error) {
        tokenExpireError(dispatch, error.message);
      }
    }
  };

  const getAllClients = async () => {
    try {
      const result = await getAllClientAPI();

      if (!result.error) {
        //
        // setClients(result.list);
      } else {
        setClients([]);
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  // const getAllMixTypes = async () => {
  //   let UserClientId = localStorage.getItem('userClientId');
  //   try {
  //     const result = await getAllMixTypeClientAPI();

  //     if (!result.error) {
  //
  //       setMixTypes(result.list);
  //     } else {
  //
  //       setMixTypes([]);
  //     }
  //   } catch (error) {
  //
  //     tokenExpireError(dispatch, error.message);
  //   }
  // };

  //   const retrieveAllSettings = async () => {
  //     try {
  //       const filterKeywords = ["management_value", "management_value_type"];
  //       const result = await retrieveAllSettingsAPI();
  //       if (!result.error) {
  //         if (result.list.length > 0) {
  //           let filteredResult = result.list.filter((item) =>
  //             filterKeywords.includes(item.setting_key)
  //           );
  //           setSettings(filteredResult);
  //         } else {
  //           showToast(
  //             globalDispatch,
  //             "Please update your settings",
  //             4000,
  //             "error"
  //           );
  //           navigate(`/${authState.role}/setting`);
  //         }
  //       } else {
  //         showToast(globalDispatch, "Please update your settings", 4000, "error");
  //         navigate(`/${authState.role}/setting`);
  //       }
  //     } catch (error) {
  //
  //       tokenExpireError(dispatch, error.message);
  //     }
  //   };

  const handleOnChangeProducerNameChange = (e) => {
    if (e.target.value !== "" || e.target.value !== null) {
      setCachedProjectProducer(Number(e.target.value));
      localStorage.setItem("ClientProjectProducerName", e.target.value);
    }
  };

  const handleOnChangeProgramName = (e) => {
    if (e.target.value !== "" || e.target.value !== null) {
      setCachedProjectClientId(Number(e.target.value));
      localStorage.setItem("ClientProjectClientId", e.target.value);
    }
  };

  const handleOnChangeTeamName = (e) => {
    if (e.target.value !== "" || e.target.value !== null) {
      setCachedProjectProjectTeamName(e.target.value);
      localStorage.setItem("ClientProjectTeamName", e.target.value);
    }
  };

  const handleOnChangeMixType = (e) => {
    if (e.target.value !== "" || e.target.value !== null) {
      setCachedProjectMixTypeId(Number(e.target.value));
      localStorage.setItem("ClientProjectMixTypeId", e.target.value);
    }
  };

  const handleOnChangeMixDateStart = (e) => {
    if (e.target.value !== "" || e.target.value !== null) {
      setCachedProjectMixDateStart(e.target.value);
      localStorage.setItem("ClientProjectMixDateStart", e.target.value);
      setCachedProjectMixDateEnd(e.target.value);
      localStorage.setItem("ClientProjectMixDateEnd", e.target.value);
    }
  };

  const handleOnChangeMixDateEnd = (e) => {
    if (e.target.value !== "" || e.target.value !== null) {
      setCachedProjectMixDateEnd(e.target.value);
      localStorage.setItem("ClientProjectMixDateEnd", e.target.value);
    }
  };

  React.useEffect(() => {
    globalDispatch({
      type: "SETPATH",
      payload: {
        path: "projects",
      },
    });
    let UserClientId = localStorage.getItem("userClientId");
    let projectProducerName =
      localStorage.getItem("ClientProjectProducerName") &&
      JSON.parse(localStorage.getItem("ClientProjectProducerName"));

    let projectClientId =
      localStorage.getItem("ClientProjectClientId") &&
      JSON.parse(localStorage.getItem("ClientProjectClientId"));
    let projectTeamName =
      localStorage.getItem("ClientProjectTeamName") &&
      JSON.parse(localStorage.getItem("ClientProjectTeamName"));
    let projectMixTypeId =
      localStorage.getItem("ClientProjectMixTypeId") &&
      JSON.parse(localStorage.getItem("ClientProjectMixTypeId"));

    let projectMixDateStart = localStorage.getItem("ClientProjectMixDateStart");
    let projectMixDateEnd = localStorage.getItem("ClientProjectMixDateEnd");

    setCachedProjectClientId(projectClientId);
    setCachedProjectProjectTeamName(projectTeamName);
    setCachedProjectMixTypeId(projectMixTypeId);
    setCachedProjectMixDateStart(projectMixDateStart);
    setCachedProjectMixDateEnd(projectMixDateEnd);
    setCachedProjectProducer(projectProducerName);

    let client_ids = [];
    if (projectClientId?.length > 0) {
      projectClientId.forEach((row) => {
        client_ids.push(row.value);
      });
    }
    // let team_name = getNonNullValue(_data.team_name);
    let team_names = [];
    if (projectTeamName?.length > 0) {
      projectTeamName.forEach((row) => {
        team_names.push(row.value);
      });
    }

    // let mix_type_id = getNonNullValue(_data.mix_type_id);
    let mix_type_ids = [];

    if (projectMixTypeId?.length > 0) {
      projectMixTypeId.forEach((row) => {
        mix_type_ids.push(row.value);
      });
    }

    let producer_names = [];

    if (projectProducerName?.length > 0) {
      projectProducerName.forEach((row) => {
        producer_names.push(row.value);
      });
    }

    let mix_date_start = getNonNullValue(cachedProjectMixDateStart);
    let mix_date_end = getNonNullValue(cachedProjectMixDateStart);
    mix_date_start = mix_date_start
      ? moment(mix_date_start).format("YYYY-MM-DD")
      : null;
    mix_date_end = mix_date_end
      ? moment(mix_date_end).format("YYYY-MM-DD")
      : null;

    if (mix_date_start && mix_date_end && mix_date_start > mix_date_end) {
      setError("mix_date_start", {
        type: "manual",
        message: "Mix Date Start must be less than Mix Date End",
      });
      setIsLoading(false);
      return;
    }

    if (
      producer_names?.length > 0 ||
      client_ids?.length > 0 ||
      team_names?.length > 0 ||
      mix_type_ids?.length > 0 ||
      projectMixDateStart ||
      projectMixDateEnd
    ) {
      let filter = {
        is_impersonate: false,

        client_id: UserClientId ? Number(UserClientId) : null,
        producer_name: projectProducerName,
        team_name: projectTeamName,

        mix_type_id: projectMixTypeId ? Number(projectMixTypeId) : null,
        mix_date_start: projectMixDateStart,
        mix_date_end: projectMixDateEnd,
      };
      (async function () {
        setIsLoading(true);
        // await retrieveAllSettings();
        await getAllProducers();
        await getAllProjects();
        await getAllClients();
        await getAllMixTypes();
        setIsLoading(false);
      })();

      if (!pageSizeFromLocalStorage) {
        (async function () {
          await getData(1, pageSize, removeKeysWhenValueIsNull(filter));
        })();
      } else {
        (async function () {
          await getData(
            1,
            pageSizeFromLocalStorage,
            removeKeysWhenValueIsNull(filter)
          );
        })();
      }
    } else {
      (async function () {
        setIsLoading(true);
        // await retrieveAllSettings();
        await getAllProducers();
        await getAllProjects();
        await getAllClients();
        await getAllMixTypes();
        setIsLoading(false);
      })();

      if (!pageSizeFromLocalStorage) {
        (async function () {
          await getData(1, pageSize);
        })();
      } else {
        (async function () {
          await getData(1, pageSizeFromLocalStorage);
        })();
      }
    }

    //
  }, []);

  const handleSelectedProducers = (names) => {
    if (names.length === 0) {
      setSelectedProducers([]);
      localStorage.setItem("ClientProjectProducerName", JSON.stringify(""));
      setCachedProjectProducer([]);
    } else {
      setSelectedProducers(names);
      localStorage.setItem("ClientProjectProducerName", JSON.stringify(names));
      setCachedProjectProducer(names);
    }

    if (names?.length < selectedProducers.length) {
      setReFilter(!reFilter);
    }
  };

  const orientationChangeHandler = (e) => {
    const portrait = e.matches;

    if (portrait && window.innerWidth <= 600) {
      showToast(
        globalDispatch,
        "Please rotate your device to landscape orientation for the best experience.",
        40000,
        "warning"
      );
    }
  };

  window
    .matchMedia("(orientation: portrait)")
    .addEventListener("change", orientationChangeHandler);

  const programName = localStorage.getItem("userProgramName") || "";

  return (
    <div className="p-4 h-full max-w-screen md:p-4 lg:p-6 xl:p-8">
      <div className="shadow-default x">
        <div className="flex flex-row justify-between items-center p-3 px-4 mb-3 w-full rounded border shadow border-strokedark bg-boxdark">
          <div className="flex gap-1">
            <h4 className="text-2xl font-semibold text-white dark:text-white">
              Projects /
            </h4>
            <h4 className="text-2xl font-medium text-white">
              &nbsp;Welcome {programName}
            </h4>
          </div>
          <LiveDateTime />
        </div>

        <div className="rounded border shadow-default border-strokedark bg-boxdark dark:border-strokedark dark:bg-boxdark">
          <div className="px-4 py-6 mb-4 border-b project_search border-strokedark sm:px-6 2xl:px-9 dark:border-strokedark">
            <form onSubmit={handleSubmit(onSubmit)} className="w-full">
              <div className="flex gap-3 items-center">
                <div className="flex w-[23%]  flex-col">
                  <label className="mb-1.5 text-sm font-medium text-white">
                    Team Name
                  </label>
                  <FormMultiSelect
                    className="h-[38px]"
                    values={selectedTeamNames}
                    onValuesChange={handleSelectedTeamNames}
                    options={teamNamesForSelect}
                    placeholder="Team Name"
                  />
                </div>

                <div className="flex w-[23%]  flex-col">
                  <label className="mb-1.5 text-sm font-medium text-white">
                    Mix Type
                  </label>
                  <FormMultiSelect
                    className="h-[38px]"
                    values={selectedMixTypeIds}
                    onValuesChange={handleSelectedMixTypeIds}
                    options={mixTypesForSelect}
                    placeholder="Mix Type"
                  />
                </div>

                <div className="w-[46%]">
                  <div className="flex gap-3 items-center">
                    <label className="mb-1.5 w-[48.5%] text-sm font-medium text-white">
                      Mix Start Date
                    </label>
                    <label className="mb-1.5 w-[46%] text-sm font-medium text-white">
                      Mix End Date
                    </label>
                  </div>
                  <DateRangePicker
                    isOutsideRange={() => false}
                    endDateArialLabel="Mix Date End"
                    startDateArialLabel="Mix Date Start"
                    endDatePlaceholderText="Mix Date End"
                    startDatePlaceholderText="Mix Date Start"
                    displayFormat="MM-DD-YYYY"
                    onFocusChange={(focusedInput) =>
                      setFocusedInput(focusedInput)
                    }
                    focusedInput={focusedInput}
                    onDatesChange={({ startDate, endDate }) => {
                      setValue("mix_date_start", startDate);
                      setValue("mix_date_end", endDate);
                      setCachedProjectMixDateStart(startDate);
                      setCachedProjectMixDateEnd(endDate);
                    }}
                    startDate={
                      cachedProjectMixDateStart
                        ? moment(cachedProjectMixDateStart)
                        : ""
                    }
                    endDate={
                      cachedProjectMixDateEnd
                        ? moment(cachedProjectMixDateEnd)
                        : ""
                    }
                    startDateId="mix_date_start"
                    endDateId="mix_date_end"
                    customInputIcon={null}
                    customArrowIcon={null}
                    className="w-2/5"
                  />
                </div>
              </div>
              <div className="flex gap-2 items-center mt-3">
                <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 className="custom-overflow min-h-[200px] w-full overflow-x-auto  pb-4 pt-6 md:pb-6 2xl:pb-10">
            <table className="w-full table-auto">
              <thead className="divide-y divide-[#9ca3ae80] bg-meta-4">
                <tr className="">
                  {columns.map((column, i) => (
                    <th
                      key={i}
                      scope="col"
                      className="px-4 py-3 text-xs font-medium tracking-wider text-left uppercase whitespace-nowrap text-bodydark1"
                    >
                      {column.header}
                      <span>
                        {column.isSorted
                          ? column.isSortedDesc
                            ? " ▼"
                            : " ▲"
                          : ""}
                      </span>
                    </th>
                  ))}
                </tr>
              </thead>
              <tbody className="cursor-pointer">
                {!isLoading ? (
                  currentTableData.map((row, i) => (
                    <ClientProjectColumns row={row} key={i} indexe={i} />
                  ))
                ) : isLoading && currentTableData.length === 0 ? (
                  <tr>
                    <td colSpan={columns.length} className="px-4 py-8">
                      <div className="flex justify-center items-center">
                        <span classNasme="relative text-xl font-semibold text-white animate-pulse">
                          <ClipLoader color="#fff" size={20} className="mr-3" />{" "}
                          Loading Projects...
                        </span>
                      </div>
                    </td>
                  </tr>
                ) : !isLoading && currentTableData.length === 0 ? (
                  <tr>
                    <td colSpan={columns.length} className="px-4 py-8">
                      <div className="flex justify-center items-center">
                        <span className="text-xl font-semibold text-white">
                          No data found
                        </span>
                      </div>
                    </td>
                  </tr>
                ) : isLoading && currentTableData.length > 0 ? (
                  <tr>
                    <td colSpan={columns.length} className="px-4 py-8">
                      <div className="flex justify-center items-center">
                        <span className="relative text-xl font-semibold text-white animate-pulse">
                          <ClipLoader color="#fff" size={20} className="mr-3" />{" "}
                          Loading Projects...
                        </span>
                      </div>
                    </td>
                  </tr>
                ) : null}
              </tbody>
            </table>
          </div>
          {currentTableData.length > 0 && !isLoading ? (
            <div className="px-4 py-10 sm:px-6 2xl:px-9">
              <PaginationBar
                currentPage={currentPage}
                pageCount={pageCount}
                pageSize={pageSize}
                canPreviousPage={canPreviousPage}
                canNextPage={canNextPage}
                updatePageSize={updatePageSize}
                previousPage={previousPage}
                nextPage={nextPage}
                dataTotal={dataTotal}
                callDataAgain={callDataAgain}
                setCurrentPage={setPage}
              />
            </div>
          ) : null}
        </div>
      </div>
    </div>
  );
};

export default ClientListProjectPage;
