import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { yupResolver } from "@hookform/resolvers/yup";
import AddButton from "Components/AddButton";
import CustomSelect2 from "Components/CustomSelect2";
import FormMultiSelect from "Components/FormMultiSelect";
import LiveDateTime from "Components/LiveDateTime/LiveDateTime";
import ManagerProjectRow from "Components/manager/managerProjectRow";
import PaginationBar from "Components/PaginationBar";
import html2canvas from "html2canvas";
import jsPDF from "jspdf";
import moment from "moment";
import React, { useState } from "react";
import { DateRangePicker } from "react-dates";
import { useForm } from "react-hook-form";
import { useLocation, useNavigate } from "react-router-dom";
import { ClipLoader } from "react-spinners";
import { AuthContext, tokenExpireError } from "Src/authContext";
import { GlobalContext, showToast } from "Src/globalContext";
import {
  addMediaAPI,
  retrieveAllMediaAPI,
} from "Src/services/clientProjectDetailsService";
import { getAllClientsFilterManagerAPI } from "Src/services/clientService";
import { sendEmailAPIV3 } from "Src/services/emailService";
import {
  getAllMembersForManager,
  retrieveAllForClientForManager,
  retrieveAllForMixSeasonForManager,
  retrieveAllForMixTypeForManager,
  retrieveAllProjectManagerAPI,
} from "Src/services/managerServices";
import { updateProjectAPI } from "Src/services/projectService";
import { retrieveAllSettingsAPI } from "Src/services/settingService";
import { getUserDetailsByIdAPI } from "Src/services/userService";
import { uploadS3FilesAPI } from "Src/services/workOrderService";
import {
  getNonNullValue,
  removeKeysWhenValueIsNull,
  sortSeasonAsc,
} from "Utils/utils";
import * as yup from "yup";

const columns = [
  {
    header: "pay",
    accessor: "checkbox",
    isSorted: false,
    isSortedDesc: false,
    mappingExist: false,
    mappings: {},
  },
  {
    header: "Mix Date",
    accessor: "mix_date",
    isSorted: false,
    isSortedDesc: false,
    mappingExist: false,
    mappings: {},
  },
  {
    header: "Program/Team",
    accessor: "program&team",
    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_status",
    isSorted: false,
    isSortedDesc: false,
    mappingExist: false,
    mappings: {},
  },
  {
    header: "RS/ED",
    accessor: "Td&Ed",
    isSorted: false,
    isSortedDesc: false,
    mappingExist: false,
    mappings: {},
  },
  // {
  //   header: 'Content Status',
  //   accessor: 'content_status',
  //   isSorted: false,
  //   isSortedDesc: false,
  //   mappingExist: false,
  //   mappings: {},
  // },
  // {
  //   header: 'T/D/M/E/NT',
  //   accessor: 'ledger',
  //   isSorted: false,
  //   isSortedDesc: false,
  //   mappingExist: false,
  //   mappings: {},
  // },
  {
    header: "STATUS",
    accessor: "status",
    isSorted: false,
    isSortedDesc: false,
    mappingExist: false,
    mappings: {},
  },
];

const COLORS = [
  {
    id: 0,
    color: "#B31B1B",
    name: "Red",
  },
  {
    id: 1,
    color: "#6CC551",
    name: "Green",
  },
];

const ListProjectPage = () => {
  const { dispatch, state: authState } = React.useContext(AuthContext);
  const { dispatch: globalDispatch } = React.useContext(GlobalContext);
  const Teamtypes = [
    { id: 1, value: "All Girl" },
    { id: 2, value: "Co-ed" },
    { id: 3, value: "TBD" },
  ];
  const [startDate, setStartDate] = useState();
  const [endDate, setEndDate] = useState();
  const [isLoading, setIsLoading] = React.useState(false);

  const [clientsForSelect, setClientsForSelect] = React.useState([]);
  const [selectedClientIds, setSelectedClientIds] = React.useState([]);
  const [selectedTeamTypeIds, setSelectedTeamTypeIds] = React.useState(null);

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

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

  const [mixTypesForSelect, setMixTypesForSelect] = React.useState([]);
  const [selectedMixTypeIds, setSelectedMixTypeIds] = React.useState([]);

  const [settings, setSettings] = React.useState([]);
  const [currentTableData, setCurrentTableData] = React.useState([]);
  const [focusedInput, setFocusedInput] = React.useState(false);
  // const [pageSize, setPageSize] = React.useState(10);
  const [pageCount, setPageCount] = React.useState(0);
  const [CompleteCount, setCompleteCount] = React.useState(0);
  const [UnfilteredTotalCount, setUnfilteredTotalCount] = 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 [cachedProjectClientId, setCachedProjectClientId] = React.useState("");
  const [cachedProjectProjectTeamName, setCachedProjectProjectTeamName] =
    React.useState("");
  const [cachedProjectMixTypeId, setCachedProjectMixTypeId] =
    React.useState("");
  const [mixSeasons, setMixSeasons] = React.useState([]);
  const [cachedProjectMixDateStart, setCachedProjectMixDateStart] =
    React.useState("");
  const [cachedProjectProducers, setCachedProjectProducers] =
    React.useState("");
  const [cachedProjectMixDateEnd, setCachedProjectMixDateEnd] =
    React.useState("");
  const [thisWeekSelected, setThisWeekSelected] = React.useState(false);
  const [loadProducers, setLoadProducers] = React.useState(false);
  const location = useLocation();

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

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

  console.log(clientsForSelect);

  const [HidecompletedStatus, setHideCompletedStatus] = React.useState(false);

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

  const [selectedProjectIdsForEdit, setSelectedProjectIdsForEdit] =
    React.useState([]);

  const [isEditPayment, setIsEditPayment] = React.useState(false);

  const [paymentStatus, setPaymentStatus] = React.useState(null);

  React.useEffect(() => {
    (async function () {
      await getAllProducers();
    })();
  }, [location.pathname]);

  console.log(pageSize, "pagesize");

  const getAllMixSeasons = async () => {
    try {
      let result;

      if (selectedProducers.length > 0) {
        result = await retrieveAllForMixSeasonForManager(
          1,
          5000,
          removeKeysWhenValueIsNull({
            member_ids: selectedProducers.map((elem) => elem.value) ?? null,
          })
        );
      } else {
        result = await retrieveAllForMixSeasonForManager(
          1,
          5000,
          removeKeysWhenValueIsNull({
            member_ids:
              producersForSelect.length > 0
                ? producersForSelect.map((elem) => elem.value)
                : null,
          })
        );
      }

      const { list, total, limit, num_pages, page } = result;
      if (!result.error) {
        setMixSeasons(sortSeasonAsc(list));
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  const handleSelectedProjectIdForEdit = (ProjectId) => {
    setSelectedProjectIdsForEdit((prev) => [...prev, ProjectId]);
  };

  const handleUnSelectedProjectIdForEdit = (ProjectId) => {
    setSelectedProjectIdsForEdit((prev) =>
      prev.filter((item) => item.id !== ProjectId.id)
    );
  };

  React.useEffect(() => {
    let projectClientId =
      localStorage.getItem("managerProjectClientId") &&
      JSON.parse(localStorage.getItem("managerProjectClientId"));
    let projectTeamName =
      localStorage.getItem("managerProjectTeamName") &&
      JSON.parse(localStorage.getItem("managerProjectTeamName"));
    let projectMixTypeId =
      localStorage.getItem("managerProjectMixTypeId") &&
      JSON.parse(localStorage.getItem("managerProjectMixTypeId"));
    let projectProducers =
      localStorage.getItem("managerProjectProducers") &&
      JSON.parse(localStorage.getItem("managerProjectProducers"));
    let projectMixDateStart = localStorage.getItem(
      "managerProjectMixDateStart"
    );
    let projectMixDateEnd = localStorage.getItem("managerProjectMixDateEnd");

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

    projectMixTypeId &&
      projectMixTypeId?.length > 0 &&
      setSelectedMixTypeIds(projectMixTypeId);
    projectClientId &&
      projectClientId?.length > 0 &&
      setSelectedClientIds(projectClientId);
    projectTeamName &&
      projectTeamName?.length > 0 &&
      setSelectedTeamNames(projectTeamName);
    projectProducers &&
      projectProducers?.length > 0 &&
      setSelectedProducers(projectProducers);
  }, []);

  // const companyName = localStorage.getItem('companyName');

  function shortenYearRange(yearRange) {
    if (!yearRange) {
      return "mixSeason";
    } else if (!/\d{4}-\d{4}/.test(yearRange)) {
      return yearRange;
    }
    // Split the year range by "-"
    const [startYear, endYear] = yearRange.split("-");

    // Extract the last two digits of each year
    const shortStartYear = startYear.slice(2);
    const shortEndYear = endYear.slice(2);

    // Concatenate the shortened years
    return shortStartYear + "-" + shortEndYear;
  }

  async function handleUploadLicense(
    id,
    mix_season_id,
    programName,
    team_name,
    logo
  ) {
    console.log(programName, "programName", team_name, "team_name", id);
    let mixSeasonName =
      mixSeasons.find((elem) => elem.id == mix_season_id) || "";
    mixSeasonName = mixSeasonName?.name;

    try {
      const input = document.querySelector(`#printable-component-${id}`);
      console.log(input, "input");
      const p = document.querySelector("#pop");

      const canvas = await html2canvas(input, {
        allowTaint: true,
        useCors: true,
        logging: true,
        proxy: logo,
      });

      const imgData = canvas.toDataURL("image/png");
      const pdf = new jsPDF("p", "mm", "legal");
      const imgWidth = 210; // A4 width in mm
      const imgHeight = (canvas.height * imgWidth) / canvas.width;
      pdf.addImage(imgData, "PNG", 0, 0, imgWidth, imgHeight);

      const blobPDF = new Blob([pdf.output("blob")], {
        type: "application/pdf",
      });

      const formData = new FormData();
      formData.append(
        "files",
        blobPDF,
        `License_${programName}_${team_name}_${mixSeasonName}.pdf`
      );

      const result = await uploadS3FilesAPI(formData);

      if (!result.error) {
        const payload = {
          project_id: id,
          url: result.attachments,
          type: "License",
          description: shortenYearRange(mixSeasonName),
          is_paid: 1,
          is_music: 1,
          status: 1,
          is_member: 1,
        };
        const res = await addMediaAPI(payload);
      } else {
        console.error("Error uploading to S3:", result.error);
      }
    } catch (error) {
      console.error("Error handling upload license:", error);
    }
  }

  const LicenseMail = async (
    status,
    id,
    pStatus,
    team_name,
    program,
    program_owner_email,
    mix_season_id,
    companyName,
    logo
  ) => {
    const result = await retrieveAllMediaAPI({
      page: 1,
      limit: 1,

      filter: {
        is_member: 1,
        project_id: id,
      },
    });

    let mixSeasonName =
      mixSeasons.find((elem) => elem.id == mix_season_id) || "";
    mixSeasonName = mixSeasonName?.name;
    const isLicense =
      result?.list.find(
        (elem) => elem.description == shortenYearRange(mixSeasonName)
      ) || null;

    if (status == 1 && pStatus !== 1 && !result?.error && !isLicense) {
      const payloade = {
        from: "myeq@equalityrecords.com",
        to: program_owner_email,
        subject: `Your Mix for  ${team_name} by ${companyName} is Ready!`,
        body: `
              <p>Hello <b>${program}</b> !</p>
              <p>We are excited to let you know that your music and license for <b>${team_name}</b> is now available for download! Please login to myEQ to download your files. Open your team's project, click the MEDIA tab, then scroll down to License and Music section.</p>
               <a href="https://equalityrecords.com/client/login" style="text-decoration: none;">
            <button style="display: inline-block; padding: 8px 20px; background-color: #007bff; color: #ffffff; border: none; border-radius: 4px; cursor: pointer;">Login</button>
        </a>

              <p>ENJOY!</p>
              <p>All the best,</p>
              <p>${companyName} Admin Team</p>
        `,
      };

      await handleUploadLicense(id, mix_season_id, program, team_name, logo);
      const emailResult =
        parseInt(SubscriptionType) !== 1 && (await sendEmailAPIV3(payloade));
    }
  };

  function callDataAgain(page) {
    (async function () {
      setIsLoading(true);
      // await getData(currentPage - 1 > 0 ? currentPage - 1 : 0, pageSize);

      let projectClientId =
        localStorage.getItem("managerProjectClientId") &&
        JSON.parse(localStorage.getItem("managerProjectClientId"));
      let projectTeamName =
        localStorage.getItem("managerProjectTeamName") &&
        JSON.parse(localStorage.getItem("managerProjectTeamName"));
      let projectMixTypeId =
        localStorage.getItem("managerProjectMixTypeId") &&
        JSON.parse(localStorage.getItem("managerProjectMixTypeId"));
      let projectMixDateStart = localStorage.getItem(
        "managerProjectMixDateStart"
      );
      let projectMixDateEnd = localStorage.getItem("managerProjectMixDateEnd");
      let projectProducers =
        localStorage.getItem("managerProjectProducers") &&
        JSON.parse(localStorage.getItem("managerProjectProducers"));

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

      let producers = [];

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

      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 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 (
        projectClientId?.length > 0 ||
        team_names?.length > 0 ||
        projectMixTypeId?.length > 0 ||
        projectMixDateStart ||
        producers?.length > 0 ||
        projectMixDateEnd
      ) {
        let filter = {
          client_ids: client_ids ?? null,
          team_names: team_names ?? null,
          mix_type_ids: 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);
    })();
  }

  const updateProjectsPaymentStatus = async (projectIds, status) => {
    try {
      setIsLoading(true);
      const promises = projectIds.map((id) =>
        updateProjectAPI({
          id: id.id,
          discount: id.discount,
          payment_status: parseInt(status),
        })
      );
      const result = await Promise.all(promises); // program_owner_name:row.program_owner_name,
      //                       program_name:row.program_name,team_name:row.team_name

      console.log(projectIds, "projectIds");

      if (!result.error) {
        const License = projectIds.map((id) =>
          LicenseMail(
            status,
            id.id,
            id.pStatus,
            id.team_name,
            id.program_name,
            id.program_owner_email,
            id.mix_season_id,
            id?.company_name,
            id?.logo
          )
        );
        await Promise.all(License);
        await ShowCompletedProjects(HidecompletedStatus);
        setSelectedProjectIdsForEdit([]);
        showToast(
          globalDispatch,
          "All selected projects status updated successfully",
          4000,
          "success"
        );
      }
      // program_owner_name:row.program_owner_name,
      //                       program_name:row.program_name,team_name:row.team_name

      setIsLoading(false);
    } catch (error) {
      showToast(
        globalDispatch,
        "Error updating projects Status payment status",
        4000,
        "error"
      );
      setIsLoading(false);
      console.error("Error updating projects Status:", error);
    }
  };

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

      let projectClientId =
        localStorage.getItem("managerProjectClientId") &&
        JSON.parse(localStorage.getItem("managerProjectClientId"));
      let projectTeamName =
        localStorage.getItem("managerProjectTeamName") &&
        JSON.parse(localStorage.getItem("managerProjectTeamName"));
      let projectMixTypeId =
        localStorage.getItem("managerProjectMixTypeId") &&
        JSON.parse(localStorage.getItem("managerProjectMixTypeId"));
      let projectProducers =
        localStorage.getItem("managerProjectProducers") &&
        JSON.parse(localStorage.getItem("managerProjectProducers"));
      let projectMixDateStart = localStorage.getItem(
        "managerProjectMixDateStart"
      );
      let projectMixDateEnd = localStorage.getItem("managerProjectMixDateEnd");

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

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

      let producers = [];

      if (projectProducers?.length > 0) {
        projectProducers.forEach((row) => {
          producers.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 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 (
        client_ids?.length > 0 ||
        team_names?.length > 0 ||
        mix_type_ids?.length > 0 ||
        producers?.length > 0 ||
        projectMixDateStart ||
        projectMixDateEnd
      ) {
        let filter = {
          client_ids: client_ids ?? null,
          team_names: team_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)
        );
        setIsLoading(false);
      } else {
        await getData(
          1,
          pageSizeFromLocalStorage ? pageSizeFromLocalStorage : pageSize
        );
        setIsLoading(false);
      }
    })();
  }, [reFilter]);

  const navigate = useNavigate();

  const schema = yup.object({
    client_ids: yup.array(),
    team_names: yup.array(),
    mix_type_ids: yup.array(),
    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 projectClientId =
        localStorage.getItem("managerProjectClientId") &&
        JSON.parse(localStorage.getItem("managerProjectClientId"));
      let projectTeamName =
        localStorage.getItem("managerProjectTeamName") &&
        JSON.parse(localStorage.getItem("managerProjectTeamName"));
      let projectMixTypeId =
        localStorage.getItem("managerProjectMixTypeId") &&
        JSON.parse(localStorage.getItem("managerProjectMixTypeId"));
      let projectMixDateStart = localStorage.getItem(
        "managerProjectMixDateStart"
      );
      let projectMixDateEnd = localStorage.getItem("managerProjectMixDateEnd");
      let projectProducers =
        localStorage.getItem("managerProjectProducers") &&
        JSON.parse(localStorage.getItem("managerProjectProducers"));

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

      let producers = [];

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

      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 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 (
        projectClientId?.length > 0 ||
        team_names?.length > 0 ||
        projectMixTypeId?.length > 0 ||
        projectMixDateStart ||
        producers?.length > 0 ||
        projectMixDateEnd
      ) {
        let filter = {
          client_ids: client_ids ?? null,
          team_names: team_names ?? null,
          mix_type_ids: mix_type_ids ?? null,
          mix_date_start: projectMixDateStart,
          mix_date_end: projectMixDateEnd,
        };
        if (!pageSizeFromLocalStorage) {
          (async function () {
            await getData(1, limit, removeKeysWhenValueIsNull(filter));
          })();
        } else {
          (async function () {
            await getData(1, limit, removeKeysWhenValueIsNull(filter));
          })();
        }
      } else {
        if (!pageSizeFromLocalStorage) {
          (async function () {
            await getData(1, limit);
          })();
        } else {
          (async function () {
            await getData(1, limit);
          })();
        }
      }
      setIsLoading(false);
    })();
    localStorage.setItem("managerProjectPageSize", limit);
  }

  function ShowCompletedProjects(status) {
    (async function () {
      setIsLoading(true);
      // setPageSize(limit);

      let projectClientId =
        localStorage.getItem("managerProjectClientId") &&
        JSON.parse(localStorage.getItem("managerProjectClientId"));
      let projectTeamName =
        localStorage.getItem("managerProjectTeamName") &&
        JSON.parse(localStorage.getItem("managerProjectTeamName"));
      let projectMixTypeId =
        localStorage.getItem("managerProjectMixTypeId") &&
        JSON.parse(localStorage.getItem("managerProjectMixTypeId"));
      let projectMixDateStart = localStorage.getItem(
        "managerProjectMixDateStart"
      );
      let projectMixDateEnd = localStorage.getItem("managerProjectMixDateEnd");
      let projectProducers =
        localStorage.getItem("managerProjectProducers") &&
        JSON.parse(localStorage.getItem("managerProjectProducers"));

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

      let producers = [];

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

      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 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 (
        projectClientId?.length > 0 ||
        team_names?.length > 0 ||
        projectMixTypeId?.length > 0 ||
        projectMixDateStart ||
        projectMixDateEnd ||
        producers?.length > 0 ||
        status === true
      ) {
        let filter = {
          client_ids: client_ids ?? null,
          team_names: team_names ?? null,
          mix_type_ids: mix_type_ids ?? null,
          mix_date_start: projectMixDateStart,
          mix_date_end: projectMixDateEnd,
          payment_status_without_completed: status ? 1 : null,
        };
        if (!pageSizeFromLocalStorage) {
          (async function () {
            await getData(
              1,
              pageSizeFromLocalStorage ? pageSizeFromLocalStorage : pageSize,
              removeKeysWhenValueIsNull(filter)
            );
            setIsLoading(false);
          })();
        } else {
          (async function () {
            await getData(
              1,
              pageSizeFromLocalStorage ? pageSizeFromLocalStorage : pageSize,
              removeKeysWhenValueIsNull(filter)
            );
            setIsLoading(false);
          })();
        }
      } else {
        if (!pageSizeFromLocalStorage) {
          (async function () {
            await getData(
              1,
              pageSizeFromLocalStorage ? pageSizeFromLocalStorage : pageSize
            );
            setIsLoading(false);
          })();
        } else {
          (async function () {
            await getData(
              1,
              pageSizeFromLocalStorage ? pageSizeFromLocalStorage : pageSize
            );
            setIsLoading(false);
          })();
        }
      }
      // setIsLoading(false);
    })();
  }

  function previousPage() {
    (async function () {
      setIsLoading(true);
      // await getData(currentPage - 1 > 0 ? currentPage - 1 : 0, pageSize);

      let projectClientId =
        localStorage.getItem("managerProjectClientId") &&
        JSON.parse(localStorage.getItem("managerProjectClientId"));
      let projectTeamName =
        localStorage.getItem("managerProjectTeamName") &&
        JSON.parse(localStorage.getItem("managerProjectTeamName"));
      let projectMixTypeId =
        localStorage.getItem("managerProjectMixTypeId") &&
        JSON.parse(localStorage.getItem("managerProjectMixTypeId"));
      let projectMixDateStart = localStorage.getItem(
        "managerProjectMixDateStart"
      );
      let projectMixDateEnd = localStorage.getItem("managerProjectMixDateEnd");
      let projectProducers =
        localStorage.getItem("managerProjectProducers") &&
        JSON.parse(localStorage.getItem("managerProjectProducers"));

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

      let producers = [];

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

      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 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 (
        projectClientId?.length > 0 ||
        team_names?.length > 0 ||
        projectMixTypeId?.length > 0 ||
        projectMixDateStart ||
        producers?.length > 0 ||
        projectMixDateEnd
      ) {
        let filter = {
          client_ids: client_ids ?? null,
          team_names: team_names ?? null,
          mix_type_ids: 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 nextPage() {
    (async function () {
      setIsLoading(true);
      // await getData(
      //   currentPage + 1 <= pageCount ? currentPage + 1 : 0,
      //   pageSize
      // );

      let projectClientId =
        localStorage.getItem("managerProjectClientId") &&
        JSON.parse(localStorage.getItem("managerProjectClientId"));
      let projectTeamName =
        localStorage.getItem("managerProjectTeamName") &&
        JSON.parse(localStorage.getItem("managerProjectTeamName"));
      let projectMixTypeId =
        localStorage.getItem("managerProjectMixTypeId") &&
        JSON.parse(localStorage.getItem("managerProjectMixTypeId"));
      let projectMixDateStart = localStorage.getItem(
        "managerProjectMixDateStart"
      );
      let projectMixDateEnd = localStorage.getItem("managerProjectMixDateEnd");
      let projectProducers =
        localStorage.getItem("managerProjectProducers") &&
        JSON.parse(localStorage.getItem("managerProjectProducers"));

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

      let producers = [];

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

      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 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 (
        client_ids?.length > 0 ||
        team_names?.length > 0 ||
        mix_type_ids?.length > 0 ||
        projectMixDateStart ||
        producers?.length > 0 ||
        projectMixDateEnd
      ) {
        let filter = {
          client_ids: client_ids ?? null,
          team_names: team_names ?? null,
          mix_type_ids: mix_type_ids ?? null,
          mix_date_start: projectMixDateStart,
          mix_date_end: projectMixDateEnd,
        };

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

  async function getData(
    pageNum,
    limitNum,
    filter,
    selectedProducerss = selectedProducers
  ) {
    console.log(limitNum);
    try {
      setIsLoading(true);
      let result;

      console.log(producersForSelect, selectedProducerss);
      if (producersForSelect.length === 0) {
        let list = [];
        let total = 0;
        let limit = 0;
        let num_pages = 0;
        let page = 1;
        console.log("runnnn1");
        result = { list, total, limit, num_pages, page };
      } else if (selectedProducerss.length > 0) {
        console.log("runnnn2");
        let list = [];
        let total = 0;
        let limit = 0;
        let num_pages = 0;
        let page = 1;

        result =
          selectedProducerss.length > 0
            ? await retrieveAllProjectManagerAPI(
                pageNum,
                limitNum,
                removeKeysWhenValueIsNull({
                  ...filter,
                  member_ids:
                    selectedProducerss.map((elem) => elem.value) ?? null,
                })
              )
            : { list, total, limit, num_pages, page };
      } else if (producersForSelect.length > 0) {
        console.log("runnnn3");
        let list = [];
        let total = 0;
        let limit = 0;
        let num_pages = 0;
        let page = 1;
        result =
          producersForSelect.length > 0
            ? await retrieveAllProjectManagerAPI(
                pageNum,
                limitNum,
                removeKeysWhenValueIsNull({
                  ...filter,
                  member_ids:
                    producersForSelect.length > 0 &&
                    producersForSelect.map((elem) => elem.value),
                })
              )
            : { list, total, limit, num_pages, page };
      }

      console.log(result);
      const { list, total, limit, num_pages, page } = result;

      setCurrentTableData(list);
      setUnfilteredTotalCount(result?.total_count);
      setCompleteCount(result?.total_completed_projects);
      // setPageSize(limit);
      setPageCount(num_pages);
      setPage(page);
      setDataTotal(total);
      setCanPreviousPage(page > 1);
      setCanNextPage(page + 1 <= num_pages);
      list.length !== 0 && page !== 0 && setIsLoading(false);
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  }

  const resetForm = async () => {
    reset();
    setIsLoading(true);
    localStorage.setItem("managerProjectClientId", "");
    localStorage.setItem("managerProjectTeamName", "");
    localStorage.setItem("managerProjectMixTypeId", "");
    localStorage.setItem("managerProjectMixDateStart", "");
    localStorage.setItem("managerProjectMixDateEnd", "");
    localStorage.setItem("managerProjectPageSize", "");
    localStorage.setItem("managerProjectProducers", "");
    setCachedProjectProducers([]);
    setCachedProjectClientId("");
    setSelectedClientIds([]);
    setSelectedTeamNames([]);
    setSelectedMixTypeIds([]);
    setSelectedProducers([]);
    setCachedProjectProjectTeamName("");
    setCachedProjectMixTypeId("");
    setCachedProjectMixDateStart("");
    setCachedProjectMixDateEnd("");
    setPageSize(10);

    await getData(1, pageSize, {}, []);
    setIsLoading(false);
  };

  const onSubmit = async (_data) => {
    try {
      setIsLoading(true);
      // let client_id = getNonNullValue(_data.client_id);

      let client_ids = [];
      if (selectedClientIds.length > 0) {
        selectedClientIds.forEach((row) => {
          client_ids.push(row.value);
        });
      }
      // let team_name = getNonNullValue(_data.team_name);
      let team_names = [];
      if (selectedTeamNames.length > 0) {
        selectedTeamNames.forEach((row) => {
          team_names.push(row.value);
        });
      }
      // 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 = {
        client_ids: client_ids ?? 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 (
        !client_ids?.length &&
        !team_names?.length &&
        !mix_type_ids?.length > 0 &&
        !mix_date_start &&
        !mix_date_end &&
        !selectedProducers?.length > 0
      ) {
        setIsLoading(false);
        return;
      }

      // localStorage.setItem('managerProjectClientId', client_id ?? '');
      // localStorage.setItem('managerProjectTeamName', team_name ?? '');
      // localStorage.setItem('managerProjectMixTypeId', mix_type_id ?? '');
      localStorage.setItem("managerProjectMixDateStart", mix_date_start ?? "");
      localStorage.setItem("managerProjectMixDateEnd", 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 handleThisWeekFilter = async (e) => {
    if (thisWeekSelected) {
      try {
        setIsLoading(true);

        const startOfWeek = "";
        const endOfWeek = "";

        setCachedProjectMixDateStart(startOfWeek);
        setCachedProjectMixDateEnd(endOfWeek);

        const filter = {
          mix_date_start: startOfWeek,
          mix_date_end: endOfWeek,
        };

        // set filter to local storage
        localStorage.setItem("managerProjectMixDateStart", startOfWeek);
        localStorage.setItem("managerProjectMixDateEnd", endOfWeek);
        setThisWeekSelected(false);
        if (!pageSizeFromLocalStorage) {
          (async function () {
            await getData(1, pageSize);
          })();
        } else {
          (async function () {
            await getData(1, pageSizeFromLocalStorage);
          })();
        }

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

        const filter = {
          mix_date_start: startOfWeek,
          mix_date_end: endOfWeek,
        };

        // set filter to local storage
        localStorage.setItem("managerProjectMixDateStart", startOfWeek);
        localStorage.setItem("managerProjectMixDateEnd", 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 getAllProducers = async () => {
    try {
      const result = await getAllMembersForManager(
        localStorage.getItem("user")
      );

      if (!result.error) {
        if (result.list.length > 0) {
          let list = result.list;

          list = list.map((row) => {
            row.user_name = row.first_name + " " + row.last_name;
            return { value: row.id, label: row.user_name };
          });

          let forSelect = [];
          if (list.length > 0) {
            list.map((row, i) => {
              forSelect.push({
                value: row.value,
                label: row?.label,
              });
            });
          }

          setProducersForSelect(forSelect);
          setLoadProducers(true);
        }
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  const getAllClients = async () => {
    try {
      let result1, result2;

      if (selectedProducers.length > 0) {
        // Call API with is_first_member: 1
        result1 = await getAllClientsFilterManagerAPI(
          1,
          4000,
          removeKeysWhenValueIsNull({
            member_ids: selectedProducers.map((elem) => elem.value) ?? null,
            is_first_member: 1,
          })
        );
      } else if (producersForSelect.length > 0) {
        // Call API with is_first_member: 1

        result1 = await retrieveAllForClientForManager(
          1,
          4000,
          removeKeysWhenValueIsNull({
            is_first_member: producersForSelect.length > 0 ? 1 : null,
            member_ids:
              producersForSelect.length > 0
                ? producersForSelect.map((elem) => elem.value)
                : null,
          })
        );

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

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

        if (!result1.error) {
          if (combinedList.length > 0) {
            let forSelect = [];
            if (combinedList.length > 0) {
              combinedList.map((row, i) => {
                forSelect.push({
                  value: row.id,
                  label: row.program,
                });
              });
            }
            setClientsForSelect(forSelect);
          }
        }
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  const getAllMixTypes = async () => {
    try {
      let result;
      if (selectedProducers.length > 0) {
        result = await retrieveAllForMixTypeForManager(
          1,
          5000,
          removeKeysWhenValueIsNull({
            member_ids: selectedProducers.map((elem) => elem.value) ?? null,
          })
        );
      } else {
        result = await retrieveAllForMixTypeForManager(
          1,
          5000,
          removeKeysWhenValueIsNull({
            member_ids:
              producersForSelect.length > 0
                ? producersForSelect.map((elem) => elem.value)
                : null,
          })
        );
        if (result.error) {
          result = { list: [], total: 0, num_pages: 0, page: 0, limit: 10 };
        }
      }

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

      if (list.length > 0) {
        let forSelect = [];
        if (list.length > 0) {
          list.map((row, i) => {
            forSelect.push({
              value: row.id,
              label: row.name,
            });
          });
        }
        setMixTypesForSelect(forSelect);
      }
    } 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);
    }
  };

  selectedProjectIdsForEdit.map((elem) => {
    console.log(document.querySelector(`#printable-component-${elem.program}`));
  });

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

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

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

  const handleOnChangeMixDateStart = (e) => {
    if (e.target.value !== "" || e.target.value !== null) {
      setCachedProjectMixDateStart(e.target.value);

      localStorage.setItem("managerProjectMixDateStart", e.target.value);
      setCachedProjectMixDateEnd(e.target.value);
      localStorage.setItem("managerProjectMixDateEnd", e.target.value);
    }
  };

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

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

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

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

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

  console.log(selectedClientIds);
  const handleSelectedClientIds = (ids) => {
    if (ids.length === 0) {
      setSelectedClientIds([]);
      localStorage.setItem("managerProjectClientId", JSON.stringify(""));
      setCachedProjectClientId([]);
    } else {
      setSelectedClientIds(ids);
      localStorage.setItem("managerProjectClientId", JSON.stringify(ids));
      setCachedProjectClientId(ids);
    }

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

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

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

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

    // Only proceed if producers are loaded
    if (!loadProducers) return;

    // Run this initialization only once after producers are loaded
    const initializeData = async () => {
      setIsLoading(true);

      let projectClientId =
        localStorage.getItem("managerProjectClientId") &&
        JSON.parse(localStorage.getItem("managerProjectClientId"));
      let projectTeamName =
        localStorage.getItem("managerProjectTeamName") &&
        JSON.parse(localStorage.getItem("managerProjectTeamName"));
      let projectMixTypeId =
        localStorage.getItem("managerProjectMixTypeId") &&
        JSON.parse(localStorage.getItem("managerProjectMixTypeId"));
      let projectMixDateStart = localStorage.getItem(
        "managerProjectMixDateStart"
      );
      let projectMixDateEnd = localStorage.getItem("managerProjectMixDateEnd");
      let projectProducers =
        localStorage.getItem("managerProjectProducers") &&
        JSON.parse(localStorage.getItem("managerProjectProducers"));

      // Set cached values
      setCachedProjectClientId(projectClientId);
      setCachedProjectProjectTeamName(projectTeamName);
      setCachedProjectMixTypeId(projectMixTypeId);
      setCachedProjectMixDateStart(projectMixDateStart);
      setCachedProjectMixDateEnd(projectMixDateEnd);
      setCachedProjectProducers(projectProducers);

      // Process filter values
      let producers =
        projectProducers?.length > 0
          ? projectProducers.map((row) => row.value)
          : [];

      let client_ids =
        projectClientId?.length > 0
          ? projectClientId.map((row) => row.value)
          : [];

      let team_names =
        projectTeamName?.length > 0
          ? projectTeamName.map((row) => row.value)
          : [];

      let mix_type_ids =
        projectMixTypeId?.length > 0
          ? projectMixTypeId.map((row) => 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;
      }

      try {
        // Load required data
        await Promise.all([
          getAllClients(),
          getAllMixTypes(),
          getAllMixSeasons(),
        ]);

        // Apply filters if they exist
        if (
          client_ids.length > 0 ||
          team_names.length > 0 ||
          mix_type_ids.length > 0 ||
          projectMixDateStart ||
          producers.length > 0 ||
          projectMixDateEnd
        ) {
          const filter = {
            client_ids: client_ids.length > 0 ? client_ids : null,
            team_names: team_names.length > 0 ? team_names : null,
            mix_type_ids: mix_type_ids.length > 0 ? mix_type_ids : null,
            mix_date_start: projectMixDateStart,
            mix_date_end: projectMixDateEnd,
          };

          await getData(
            1,
            pageSizeFromLocalStorage
              ? Number(pageSizeFromLocalStorage)
              : pageSize,
            removeKeysWhenValueIsNull(filter)
          );
        } else {
          await getData(
            1,
            pageSizeFromLocalStorage
              ? Number(pageSizeFromLocalStorage)
              : pageSize
          );
        }
      } catch (error) {
        console.error("Error initializing data:", error);
      } finally {
        setIsLoading(false);
      }
    };

    initializeData();
  }, [loadProducers]); // Only depend on loadProducers

  const SubscriptionType = localStorage.getItem("UserSubscription");

  const getAllProjects = async () => {
    try {
      let result;

      result = await retrieveAllProjectManagerAPI(
        1,
        5000,
        removeKeysWhenValueIsNull({
          member_ids:
            producersForSelect.length > 0
              ? producersForSelect.map((elem) => elem.value)
              : null,
        })
      );
      if (result.error) {
        result = { list: [], total: 0, num_pages: 0, page: 0, limit: 10 };
      }

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

  React.useEffect(() => {
    const userId = null;

    (async function () {
      await getAllProjects();
    })();
  }, []);

  React.useEffect(() => {
    const userId = null;

    if (userId) {
      (async function () {
        try {
          const result = await getUserDetailsByIdAPI(userId);

          if (!result?.error) {
            localStorage.setItem("photo", result?.model?.photo);
            localStorage.setItem(
              "UserSubscription",
              result?.model?.subscription
            );
          }
        } catch (error) {}
      })();
    }
  }, []);

  const CheckAll = (e) => {
    const tableBody = document.querySelector(".table-project");
    const checkboxes = tableBody.querySelectorAll('input[type="checkbox"]');
    checkboxes.forEach((checkbox) => {
      if (e.target.checked) {
        checkbox.checked = true;
      } else {
        checkbox.checked = false;
      }
    });
  };
  const handleCheckAllChange = (event) => {
    const isChecked = event.target.checked;
    if (isChecked) {
      const allProjectIds = currentTableData.map((row) => {
        return {
          id: row.id,
          discount: row.discount,
          pstatus: row.payment_status,
          program_owner_email: row.program_owner_email,
          program_name: row.program_name,
          team_name: row.team_name,
          mix_season_id: row.mix_season_id,
          logo: row?.company_info?.license_company_logo,
          company_name: row?.company_info?.company_name,
          member_name: row?.company_info?.member_name,
        };
      });

      setSelectedProjectIdsForEdit(allProjectIds);
    } else {
      setSelectedProjectIdsForEdit([]);
    }
  };

  const getProducerName = (id) => {
    let data = producersForSelect.find((elem) => elem.value == id);

    if (data) {
      return data.label;
    } else {
      return "";
    }
  };

  // React.useEffect(() => {
  //   const userId = localStorage.getItem('user');

  //   if (userId) {
  //     (async function () {
  //       try {
  //         const result = await getUserDetailsByIdAPI(userId);

  //         if (!result?.error) {
  //           localStorage.setItem('photo', result?.model?.photo);
  //           localStorage.setItem(
  //             'UserSubscription',
  //             result?.model?.subscription
  //           );
  //         }
  //       } catch (error) {}
  //     })();
  //   }
  // }, []);
  // window.addEventListener("beforeunload", async function (event) {
  //   resetForm();
  // });

  // window.addEventListener("beforeunload", async function (event) {
  //   resetForm();
  // });

  // React.useEffect(() => {
  //   return () => {
  //     resetForm();
  //   };
  // }, []);

  const selectProducerRef = React.useRef(null);
  const selectClientRef = React.useRef(null);
  const selectMixTypeRef = React.useRef(null);

  return (
    <>
      <div className="max-w-screen h-full p-4 md:p-4 lg:p-6 xl:p-8">
        {/* Header Section */}
        <div className="mb-3 flex w-full flex-row items-center justify-between rounded border border-strokedark bg-boxdark p-3 px-4 shadow">
          <div className="flex items-end gap-1">
            <h4 className="text-2xl font-medium text-white">Projects</h4>
          </div>
          <LiveDateTime />
        </div>

        {/* Main content area with dark background */}
        <div className="shadow-default rounded border border-strokedark bg-boxdark dark:border-strokedark dark:bg-boxdark">
          {/* Header with title and action buttons */}
          <div className="flex items-center justify-between border-b border-strokedark px-4 md:px-6 2xl:px-9">
            <div className="flex items-center gap-4">
              <h4 className="my-6 text-2xl font-semibold text-white dark:text-white">
                Projects /
              </h4>

              <div className="flex items-center gap-2 text-sm font-medium text-white">
                <span
                  className="flex cursor-pointer items-center gap-2 text-sm font-medium text-white"
                  onClick={(e) => handleThisWeekFilter(e)}
                >
                  <FontAwesomeIcon icon={"calendar-days"} />
                  <span
                    className={
                      thisWeekSelected ? "text-blue-500 underline" : ""
                    }
                  >
                    This week{" "}
                  </span>
                </span>
                <span className="text-2xl font-bold text-white">/</span>
              </div>
              <div className="flex items-center gap-1 text-white">
                <h6>{CompleteCount} Completed /</h6>
                <h6>{UnfilteredTotalCount} Total</h6>
              </div>
              {/* Eye Icons */}
              {HidecompletedStatus === false && (
                <FontAwesomeIcon
                  className="ml-6 h-6 w-6 cursor-pointer text-white"
                  onClick={async () => {
                    await ShowCompletedProjects(true);
                    setHideCompletedStatus(true);
                  }}
                  icon={"eye"}
                />
              )}
              {HidecompletedStatus === true && (
                <FontAwesomeIcon
                  className="ml-6 h-6 w-6 cursor-pointer text-white"
                  onClick={async () => {
                    await ShowCompletedProjects();
                    setHideCompletedStatus(false);
                  }}
                  icon={"eye-slash"}
                />
              )}
            </div>

            <div className="flex w-1/2 flex-row items-center justify-end gap-2">
              {isEditPayment ? (
                <>
                  {selectedProjectIdsForEdit.length > 0 && (
                    <CustomSelect2
                      className="w-[160px] rounded-lg border border-strokedark bg-boxdark px-3 py-1 text-sm font-medium text-white outline-none transition focus:border-primary"
                      value={paymentStatus}
                      onChange={async (value) => {
                        await updateProjectsPaymentStatus(
                          selectedProjectIdsForEdit,
                          value
                        );
                        setPaymentStatus(value);
                      }}
                    >
                      <option value="" selected disabled>
                        Payment Status
                      </option>
                      <option value="5">Unpaid</option>
                      <option value="2">Deposit Paid</option>
                      <option value="3">Paid In Full</option>
                      <option value="1">Complete</option>
                      <option value="4">Awaiting Edit</option>
                    </CustomSelect2>
                  )}
                  <button
                    type="button"
                    className="inline-flex items-center justify-center rounded-md border border-strokedark bg-meta-7 px-6 py-2 text-sm font-medium text-white hover:bg-opacity-90"
                    onClick={(e) => setIsEditPayment(false)}
                  >
                    Cancel
                  </button>
                </>
              ) : null}
              <FontAwesomeIcon
                icon={"coins"}
                className="inline-flex cursor-pointer items-center justify-center rounded-md bg-primary px-4 py-2.5 text-sm font-medium text-white hover:bg-opacity-90"
                onClick={() => setIsEditPayment(!isEditPayment)}
              />
              <div className="flex items-center gap-2">
                <AddButton link={`/${authState.role}/add-project`} />
              </div>
            </div>
          </div>

          {/* Search filters section */}
          <div className="project_search mb-4 border-b border-strokedark px-4 py-6 sm:px-6 2xl:px-9 dark:border-strokedark">
            <div className="">
              <form onSubmit={handleSubmit(onSubmit)} className="w-full">
                <div>
                  <div className="flex items-center gap-3">
                    {/* Producer Filter */}
                    <div className="flex w-1/5 flex-col">
                      <label className="mb-1.5 text-sm font-medium text-white">
                        Producer
                      </label>

                      <FormMultiSelect
                        selectRef={selectProducerRef}
                        values={selectedProducers}
                        onValuesChange={handleSelectedProducers}
                        options={producersForSelect}
                        placeholder="Producers"
                      />
                    </div>

                    {/* Client Filter */}
                    <div className="flex w-1/5 flex-col">
                      <label className="mb-1.5 text-sm font-medium text-white">
                        Client
                      </label>
                      <FormMultiSelect
                        selectRef={selectClientRef}
                        values={selectedClientIds}
                        onValuesChange={handleSelectedClientIds}
                        options={clientsForSelect}
                        placeholder="Clients"
                      />
                    </div>

                    {/* Mix Type Filter */}
                    <div className="flex w-1/5 flex-col">
                      <label className="mb-1.5 text-sm font-medium text-white">
                        Mix Type
                      </label>
                      <FormMultiSelect
                        selectRef={selectMixTypeRef}
                        values={selectedMixTypeIds}
                        onValuesChange={handleSelectedMixTypeIds}
                        options={mixTypesForSelect}
                        placeholder="Mix Types"
                      />
                    </div>

                    {/* Date Range Picker */}
                    <div className="w-2/5">
                      <div className="flex items-center gap-3">
                        <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>

                  {/* Action Buttons */}
                  <div className="mt-3 flex items-center gap-2">
                    <button
                      type="submit"
                      className="inline-flex h-[36px] items-center justify-center rounded-md bg-primary px-4 py-2 text-sm font-medium text-white hover:bg-opacity-90"
                    >
                      Search
                    </button>
                    <button
                      onClick={resetForm}
                      type="button"
                      className="inline-flex h-[36px] items-center justify-center rounded-md border border-strokedark bg-danger px-4 py-2 text-sm font-medium text-white hover:bg-opacity-90"
                    >
                      Clear
                    </button>
                  </div>
                </div>
              </form>
            </div>
          </div>

          {/* Table Section */}

          <div className="custom-overflow min-h-[150px] w-full overflow-x-auto pb-4 pt-6 md:pb-6 2xl:pb-10">
            <table className=" w-full table-auto ">
              <thead className="bg-meta-4 dark:bg-primary/5">
                <tr className="divide-y divide-[#9ca3ae80] bg-meta-4">
                  {columns.map((column, i) => {
                    if (column.header == "pay") {
                      if (column.header == "pay" && isEditPayment) {
                        return (
                          <th
                            key={i}
                            scope="col"
                            className="whitespace-nowrap  px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-bodydark1"
                          >
                            <span>All</span>
                            <input
                              type="checkbox"
                              className="ml-2 h-4 w-4 rounded border-gray-300 bg-gray-100 text-blue-600 focus:ring-2 focus:ring-blue-500 dark:focus:ring-blue-600"
                              onChange={handleCheckAllChange}
                            />
                            <span>
                              {column.isSorted
                                ? column.isSortedDesc
                                  ? " ▼"
                                  : " ▲"
                                : ""}
                            </span>
                          </th>
                        );
                      } else {
                        return (
                          <th
                            key={i}
                            scope="col"
                            className="whitespace-nowrap  px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-bodydark1"
                          >
                            <span>
                              {column.isSorted
                                ? column.isSortedDesc
                                  ? " ▼"
                                  : " ▲"
                                : ""}
                            </span>
                          </th>
                        );
                      }
                    }
                    return (
                      <th
                        key={i}
                        scope="col"
                        className="whitespace-nowrap  px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-bodydark1"
                      >
                        {column.header}
                        <span>
                          {column.isSorted
                            ? column.isSortedDesc
                              ? " ▼"
                              : " ▲"
                            : ""}
                        </span>
                      </th>
                    );
                  })}
                </tr>
              </thead>
              {!isLoading && currentTableData.length > 0 ? (
                <tbody className="table-project cursor-pointer">
                  {currentTableData.map((row, i) => (
                    <ManagerProjectRow
                      row={row}
                      indexe={i}
                      getProducerName={getProducerName}
                      setSelectedProjectIdForEdit={
                        handleSelectedProjectIdForEdit
                      }
                      setUnSelectedProjectIdForEdit={
                        handleUnSelectedProjectIdForEdit
                      }
                      isEdit={isEditPayment}
                      selectedProjectIdsForEdit={selectedProjectIdsForEdit}
                      columns={columns}
                      key={i}
                      settings={settings}
                    />
                  ))}
                </tbody>
              ) : isLoading && currentTableData.length === 0 ? (
                <tbody>
                  <tr>
                    <td colSpan={columns.length} className="text-center">
                      <span className="trans relative top-[30px] m-4 animate-pulse whitespace-nowrap p-4 pb-8 text-xl font-semibold text-white ease-out">
                        <ClipLoader color="#fff" size={20} className="mr-3" />{" "}
                        Loading Projects...
                      </span>
                    </td>
                  </tr>
                  <tr></tr>
                  <tr></tr>
                  <tr></tr>
                  <tr></tr>
                  <tr></tr>
                </tbody>
              ) : !isLoading && 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>
              ) : (
                isLoading && (
                  <tbody>
                    <tr>
                      <td colSpan={columns.length} className="text-center">
                        <span className="trans relative top-[30px] m-4 animate-pulse whitespace-nowrap p-4 pb-8 text-xl font-semibold text-white ease-out">
                          <ClipLoader color="#fff" size={20} className="mr-3" />{" "}
                          Loading Projects...
                        </span>
                      </td>
                    </tr>
                    <tr></tr>
                    <tr></tr>
                    <tr></tr>
                    <tr></tr>
                    <tr></tr>
                  </tbody>
                )
              )}
            </table>
          </div>
          {currentTableData.length > 0 && !isLoading ? (
            <div className="px-4 py-10 sm:px-6 2xl:px-9">
              <PaginationBar
                setCurrentPage={setPage}
                dataTotal={dataTotal}
                currentPage={currentPage}
                pageCount={pageCount}
                pageSize={pageSize}
                canPreviousPage={canPreviousPage}
                canNextPage={canNextPage}
                callDataAgain={callDataAgain}
                updatePageSize={updatePageSize}
                previousPage={previousPage}
                nextPage={nextPage}
              />
            </div>
          ) : null}
        </div>
      </div>
    </>
  );
};

export default ListProjectPage;
