import { yupResolver } from "@hookform/resolvers/yup";
import AddButton from "Components/AddButton";
import PaginationBar from "Components/PaginationBar";
import moment from "moment";
import React, { useRef, useState } from "react";
import { useForm } from "react-hook-form";
import { useNavigate } from "react-router-dom";
import { AuthContext, tokenExpireError } from "Src/authContext";
import { GlobalContext, showToast } from "Src/globalContext";
import {
  getAllProjectAPI,
  retrieveAllProjectWithMultiFiltersAPI,
  updateProjectAPI,
} from "Src/services/projectService";
import {
  getNonNullValue,
  removeKeysWhenValueIsNull,
  sortSeasonAsc,
} from "Utils/utils";
import * as yup from "yup";

import { getAllClientsFilterMemberAPI } from "Src/services/clientService";

import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import FormMultiSelect from "Components/FormMultiSelect";
import LiveDateTime from "Components/LiveDateTime/LiveDateTime";
import MemberProjectRow from "Components/memberProjectRow";
import html2canvas from "html2canvas";
import jsPDF from "jspdf";
import { DateRangePicker } from "react-dates";
import "react-dates/initialize";
import "react-dates/lib/css/_datepicker.css";
import ClipLoader from "react-spinners/ClipLoader";
import "Src/index.css";
import {
  addMediaAPI,
  retrieveAllMediaAPI,
} from "Src/services/clientProjectDetailsService";
import { sendEmailAPIV3 } from "Src/services/emailService";
import { retrieveAllMixSeasonsAPI } from "Src/services/mixSeasonService";
import { getAllMixTypeAPI } from "Src/services/mixTypeServices";
import { retrieveAllSettingsAPI } from "Src/services/settingService";
import { getUserDetailsByIdAPI } from "Src/services/userService";
import { uploadS3FilesAPI } from "Src/services/workOrderService";
import { Eye, EyeOff } from "lucide-react";

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: 'Team Name',
  //   accessor: 'team_name',
  //   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: '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 [loader2, setLoader2] = useState(false);
  const [isLoading, setIsLoading] = React.useState(true);

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

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

  const refContainer = useRef(null);

  const [mixTypesForSelect, setMixTypesForSelect] = React.useState([]);
  const selectRef = useRef(null);
  const [selectedMixTypeIds, setSelectedMixTypeIds] = React.useState([]);
  const [selectedTeamTypeIds, setSelectedTeamTypeIds] = React.useState(null);

  const [settings, setSettings] = React.useState([]);
  const [currentTableData, setCurrentTableData] = React.useState([]);
  // 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 [focusedInput, setFocusedInput] = 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 [cachedProjectMixDateEnd, setCachedProjectMixDateEnd] =
    React.useState("");
  const [thisWeekSelected, setThisWeekSelected] = React.useState(false);

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

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

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

  const getAllMixSeasons = async () => {
    try {
      const result = await retrieveAllMixSeasonsAPI(1, 100, { status: 1 });
      if (!result.error) {
        setMixSeasons(sortSeasonAsc(result.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(() => {
    currentTableData.length <= 0 ? setIsLoading(true) : setLoader2(true);

    let projectClientId =
      localStorage.getItem("projectClientId") &&
      JSON.parse(localStorage.getItem("projectClientId"));
    let projectTeamName =
      localStorage.getItem("projectTeamName") &&
      JSON.parse(localStorage.getItem("projectTeamName"));
    let projectMixTypeId =
      localStorage.getItem("projectMixTypeId") &&
      JSON.parse(localStorage.getItem("projectMixTypeId"));
    let projectMixDateStart = localStorage.getItem("projectMixDateStart");
    let projectMixDateEnd = localStorage.getItem("projectMixDateEnd");

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

    projectMixTypeId &&
      projectMixTypeId?.length > 0 &&
      setSelectedMixTypeIds(projectMixTypeId);
    projectClientId &&
      projectClientId?.length > 0 &&
      setSelectedClientIds(projectClientId);
    projectTeamName &&
      projectTeamName?.length > 0 &&
      setSelectedTeamNames(projectTeamName);

    currentTableData.length <= 0 ? setIsLoading(false) : setLoader2(false);
  }, []);

  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
  ) {
    let mixSeasonName =
      mixSeasons.find((elem) => elem.id == mix_season_id) || "";
    mixSeasonName = mixSeasonName?.name;
    try {
      const input = document.querySelector(`#printable-component-${id}`);
      const p = document.querySelector("#pop");

      const canvas = await html2canvas(input, {
        allowTaint: true,
        useCors: true,
        logging: true,
        proxy: localStorage.getItem("license_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
  ) => {
    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);
      const emailResult =
        parseInt(SubscriptionType) !== 1 && (await sendEmailAPIV3(payloade));
    }
  };

  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

      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
          )
        );
        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(() => {
    currentTableData.length <= 0 ? setIsLoading(true) : setLoader2(true);

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

      let projectClientId =
        localStorage.getItem("projectClientId") &&
        JSON.parse(localStorage.getItem("projectClientId"));
      let projectTeamName =
        localStorage.getItem("projectTeamName") &&
        JSON.parse(localStorage.getItem("projectTeamName"));
      let projectMixTypeId =
        localStorage.getItem("projectMixTypeId") &&
        JSON.parse(localStorage.getItem("projectMixTypeId"));
      let projectMixDateStart = localStorage.getItem("projectMixDateStart");
      let projectMixDateEnd = localStorage.getItem("projectMixDateEnd");

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

      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 ||
        projectMixDateEnd ||
        selectedTeamTypeIds
      ) {
        console.log(selectedTeamTypeIds, "djjdjd");
        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,
          team_type: selectedTeamTypeIds ?? null,
        };

        console.log(filter, "filter");

        await getData(
          1,
          pageSizeFromLocalStorage ? pageSizeFromLocalStorage : pageSize,
          removeKeysWhenValueIsNull(filter)
        );
      } else {
        await getData(
          1,
          pageSizeFromLocalStorage ? pageSizeFromLocalStorage : pageSize
        );
      }
      setIsLoading(false);
      currentTableData.length <= 0 ? setIsLoading(false) : setLoader2(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 () {
      setLoader2(true);
      setPageSize(limit);

      let projectClientId =
        localStorage.getItem("projectClientId") &&
        JSON.parse(localStorage.getItem("projectClientId"));
      let projectTeamName =
        localStorage.getItem("projectTeamName") &&
        JSON.parse(localStorage.getItem("projectTeamName"));
      let projectMixTypeId =
        localStorage.getItem("projectMixTypeId") &&
        JSON.parse(localStorage.getItem("projectMixTypeId"));
      let projectMixDateStart = localStorage.getItem("projectMixDateStart");
      let projectMixDateEnd = localStorage.getItem("projectMixDateEnd");

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

      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
      ) {
        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),
              "global"
            );
          })();
        } else {
          (async function () {
            await getData(
              1,
              limit,
              removeKeysWhenValueIsNull(filter),
              "global"
            );
          })();
        }
      } else {
        if (!pageSizeFromLocalStorage) {
          (async function () {
            await getData(1, limit, {}, "global");
          })();
        } else {
          (async function () {
            await getData(1, limit, {}, "global");
          })();
        }
      }
      setLoader2(false);
      document.getElementById("mainContainer").scrollTo({
        top: 0,
        behavior: "smooth", // Add smooth scrolling behavior
      });
    })();
    localStorage.setItem("projectPageSize", limit);
  }

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

      let projectClientId =
        localStorage.getItem("projectClientId") &&
        JSON.parse(localStorage.getItem("projectClientId"));
      let projectTeamName =
        localStorage.getItem("projectTeamName") &&
        JSON.parse(localStorage.getItem("projectTeamName"));
      let projectMixTypeId =
        localStorage.getItem("projectMixTypeId") &&
        JSON.parse(localStorage.getItem("projectMixTypeId"));
      let projectMixDateStart = localStorage.getItem("projectMixDateStart");
      let projectMixDateEnd = localStorage.getItem("projectMixDateEnd");

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

      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 ||
        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),
              "global"
            );
            setLoader2(false);
          })();
        } else {
          (async function () {
            await getData(
              1,
              pageSizeFromLocalStorage ? pageSizeFromLocalStorage : pageSize,
              removeKeysWhenValueIsNull(filter),
              "global"
            );
            setLoader2(false);
          })();
        }
      } else {
        if (!pageSizeFromLocalStorage) {
          (async function () {
            await getData(
              1,
              pageSizeFromLocalStorage ? pageSizeFromLocalStorage : pageSize,
              {},
              "global"
            );
            setLoader2(false);
          })();
        } else {
          (async function () {
            await getData(
              1,
              pageSizeFromLocalStorage ? pageSizeFromLocalStorage : pageSize,
              {},
              "global"
            );
            setLoader2(false);
          })();
        }
      }
      // setIsLoading(false);
    })();
  }

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

      // await getData(currentPage - 1 > 0 ? currentPage - 1 : 0, pageSize);

      let projectClientId =
        localStorage.getItem("projectClientId") &&
        JSON.parse(localStorage.getItem("projectClientId"));
      let projectTeamName =
        localStorage.getItem("projectTeamName") &&
        JSON.parse(localStorage.getItem("projectTeamName"));
      let projectMixTypeId =
        localStorage.getItem("projectMixTypeId") &&
        JSON.parse(localStorage.getItem("projectMixTypeId"));
      let projectMixDateStart = localStorage.getItem("projectMixDateStart");
      let projectMixDateEnd = localStorage.getItem("projectMixDateEnd");

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

      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
      ) {
        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,
          "global"
        );
      } else {
        await getData(
          currentPage - 1,
          pageSizeFromLocalStorage ? pageSizeFromLocalStorage : pageSize,
          undefined,
          "global"
        );
      }
      setIsLoading(false);
      document.getElementById("mainContainer").scrollTo({
        top: 0,
        behavior: "smooth", // Add smooth scrolling behavior
      });
      setLoader2(false);
    })();
  }

  function nextPage() {
    (async function () {
      setLoader2(true);

      // await getData(
      //   currentPage + 1 <= pageCount ? currentPage + 1 : 0,
      //   pageSize
      // );

      let projectClientId =
        localStorage.getItem("projectClientId") &&
        JSON.parse(localStorage.getItem("projectClientId"));
      let projectTeamName =
        localStorage.getItem("projectTeamName") &&
        JSON.parse(localStorage.getItem("projectTeamName"));
      let projectMixTypeId =
        localStorage.getItem("projectMixTypeId") &&
        JSON.parse(localStorage.getItem("projectMixTypeId"));
      let projectMixDateStart = localStorage.getItem("projectMixDateStart");
      let projectMixDateEnd = localStorage.getItem("projectMixDateEnd");

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

      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 ||
        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),
          "global"
        );
      } else {
        await getData(
          currentPage + 1,
          pageSizeFromLocalStorage ? pageSizeFromLocalStorage : pageSize,
          undefined,
          "global"
        );
      }
      setIsLoading(false);
      setLoader2(false);
      document.getElementById("mainContainer").scrollTo({
        top: 0,
        behavior: "smooth", // Add smooth scrolling behavior
      });
    })();
  }

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

      let projectClientId =
        localStorage.getItem("projectClientId") &&
        JSON.parse(localStorage.getItem("projectClientId"));
      let projectTeamName =
        localStorage.getItem("projectTeamName") &&
        JSON.parse(localStorage.getItem("projectTeamName"));
      let projectMixTypeId =
        localStorage.getItem("projectMixTypeId") &&
        JSON.parse(localStorage.getItem("projectMixTypeId"));
      let projectMixDateStart = localStorage.getItem("projectMixDateStart");
      let projectMixDateEnd = localStorage.getItem("projectMixDateEnd");

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

      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
      ) {
        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,
          "global"
        );
      } else {
        await getData(
          page,
          pageSizeFromLocalStorage ? pageSizeFromLocalStorage : pageSize,
          undefined,
          "global"
        );
      }
      document.getElementById("mainContainer").scrollTo({
        top: 0,
        behavior: "smooth", // Add smooth scrolling behavior
      });
      setIsLoading(false);
      console.log(refContainer.current);
      setLoader2(false);
    })();
  }

  async function getData(pageNum, limitNum, filter, loaderType = "basic") {
    try {
      loaderType === "basic" ? setIsLoading(true) : setLoader2(true);
      // const result = await retrieveAllProjectAPI(pageNum, limitNum, filter);
      const result = await retrieveAllProjectWithMultiFiltersAPI(
        pageNum,
        limitNum,
        filter
      );
      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);
      loaderType === "basic" ? setIsLoading(false) : setLoader2(false);
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  }

  const resetForm = async () => {
    reset();
    setIsLoading(true);
    localStorage.setItem("projectClientId", "");
    localStorage.setItem("projectTeamName", "");
    localStorage.setItem("projectMixTypeId", "");
    localStorage.setItem("projectMixDateStart", "");
    localStorage.setItem("projectMixDateEnd", "");
    localStorage.setItem("projectPageSize", "");
    setCachedProjectClientId("");
    setSelectedClientIds([]);
    setSelectedTeamNames([]);
    setSelectedMixTypeIds([]);
    setCachedProjectProjectTeamName("");
    setCachedProjectMixTypeId("");
    setCachedProjectMixDateStart("");
    setCachedProjectMixDateEnd("");
    setPageSize(10);

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

  const onSubmit = async (_data) => {
    try {
      setLoader2(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",
        });
        setLoader2(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,
        team_type: selectedTeamTypeIds,
      };

      //

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

      // localStorage.setItem('projectClientId', client_id ?? '');
      // localStorage.setItem('projectTeamName', team_name ?? '');
      // localStorage.setItem('projectMixTypeId', mix_type_id ?? '');
      localStorage.setItem("projectMixDateStart", mix_date_start ?? "");
      localStorage.setItem("projectMixDateEnd", 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)
          );
        })();
      }

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

  const handleThisWeekFilter = async (e) => {
    if (thisWeekSelected) {
      try {
        setLoader2(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("projectMixDateStart", startOfWeek);
        localStorage.setItem("projectMixDateEnd", endOfWeek);
        setThisWeekSelected(false);
        if (!pageSizeFromLocalStorage) {
          (async function () {
            await getData(1, pageSize);
          })();
        } else {
          (async function () {
            await getData(1, pageSizeFromLocalStorage);
          })();
        }

        setLoader2(false);
      } catch (error) {
        tokenExpireError(dispatch, error.message);
      }
    } else {
      try {
        setLoader2(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("projectMixDateStart", startOfWeek);
        localStorage.setItem("projectMixDateEnd", endOfWeek);

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

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

  const getAllClients = async () => {
    try {
      const result = await getAllClientsFilterMemberAPI();
      if (!result.error) {
        if (result.list.length > 0) {
          let forSelect = [];
          if (result.list.length > 0) {
            console.log(result.list);
            result.list.map((row, i) => {
              forSelect.push({
                value: row.id,
                label: row.program,
              });
            });
          }
          setClientsForSelect(forSelect);
        }
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  const getAllMixTypes = async () => {
    try {
      const result = await getAllMixTypeAPI();
      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 getAllProjects = async () => {
    try {
      const result = await getAllProjectAPI();
      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 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 handleOnChangeProgramName = (e) => {
  //   if (e.target.value !== '' || e.target.value !== null) {
  //     setCachedProjectClientId(Number(e.target.value));
  //     localStorage.setItem('projectClientId', e.target.value);
  //   }
  // };

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

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

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

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

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

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

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

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

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

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

  const handleSelectedTeamTypeIds = (ids) => {
    if (ids.length === 0) {
      setSelectedTeamTypeIds([]);
      // localStorage.setItem("projectMixTypeId", JSON.stringify(""));
      // setCachedProjectMixTypeId([]);
    } else {
      // localStorage.setItem("projectMixTypeId", JSON.stringify(ids));
      // setCachedProjectMixTypeId(ids);
      setSelectedTeamTypeIds(ids);
    }

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

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

    let projectClientId =
      localStorage.getItem("projectClientId") &&
      JSON.parse(localStorage.getItem("projectClientId"));
    let projectTeamName =
      localStorage.getItem("projectTeamName") &&
      JSON.parse(localStorage.getItem("projectTeamName"));
    let projectMixTypeId =
      localStorage.getItem("projectMixTypeId") &&
      JSON.parse(localStorage.getItem("projectMixTypeId"));
    let projectMixDateStart = localStorage.getItem("projectMixDateStart");
    let projectMixDateEnd = localStorage.getItem("projectMixDateEnd");

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

    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 ||
      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,
      };
      (async function () {
        setIsLoading(true);
        await retrieveAllSettings();
        await getAllProjects();
        await getAllClients();
        await getAllMixTypes();
        await getAllMixSeasons();
        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 getAllProjects();
        await getAllClients();
        await getAllMixTypes();
        await getAllMixSeasons();
        setIsLoading(false);
      })();

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

    //
  }, []);

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

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

  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([]);
    }
  };
  console.log(currentTableData, loader2, loading);

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

  return (
    <>
      <div
        className="max-w-screen h-full p-4 md:p-4 lg:p-6 xl:p-8"
        ref={refContainer}
      >
        {/* {loader2 ? <Spinner /> : null} */}

        {/* Header Section */}
        <div className="mb-3 flex w-full flex-row items-center justify-between rounded border border-boxdark 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 && (
                <Eye
                  className="ml-6 h-6 w-6 cursor-pointer text-white hover:text-blue-500"
                  onClick={async () => {
                    await ShowCompletedProjects(true);
                    setHideCompletedStatus(true);
                  }}
                />
              )}
              {HidecompletedStatus === true && (
                <EyeOff
                  className="ml-6 h-6 w-6 cursor-pointer text-white hover:text-blue-500"
                  onClick={async () => {
                    await ShowCompletedProjects();
                    setHideCompletedStatus(false);
                  }}
                  icon={"eye-slash"}
                />
              )}
            </div>
            <div className="flex items-center gap-2">
              {parseInt(SubscriptionType) !== 1 && (
                <>
                  {isEditPayment && (
                    <button
                      className="inline-flex max-h-8  items-center justify-center rounded bg-danger px-4 py-2.5 font-medium text-white hover:bg-opacity-90"
                      onClick={() => setIsEditPayment(false)}
                    >
                      Cancel
                    </button>
                  )}
                  <button
                    className="inline-flex max-h-8  items-center justify-center rounded bg-primary px-4 py-2.5 font-medium text-white hover:bg-opacity-90"
                    onClick={() => setIsEditPayment(!isEditPayment)}
                  >
                    <FontAwesomeIcon icon={"coins"} />
                  </button>
                </>
              )}
              <button
                className="float-right rounded bg-primary px-2 py-1.5 text-sm font-semibold text-white hover:bg-primary/90"
                type="button"
                onClick={() => {
                  navigate(`/${authState.role}/master-project-view`);
                }}
              >
                Master Project View
              </button>
              <AddButton link={`/${authState.role}/add-project`} />
            </div>
          </div>

          {/* Search filters section - Updated to match ListClientPage style */}
          <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 className="flex items-center gap-3">
                  {/* Program Select */}
                  <div className="flex w-1/5 flex-col">
                    <label className="mb-1.5 text-sm font-medium text-white">
                      Program
                    </label>
                    <FormMultiSelect
                      selectRef={selectClientRef}
                      values={selectedClientIds}
                      onValuesChange={handleSelectedClientIds}
                      options={clientsForSelect}
                      placeholder="Program"
                    />
                  </div>

                  {/* Team Select */}
                  <div className="flex w-1/5 flex-col">
                    <label className="mb-1.5 text-sm font-medium text-white">
                      Team
                    </label>
                    <FormMultiSelect
                      selectRef={selectTeamRef}
                      values={selectedTeamNames}
                      onValuesChange={handleSelectedTeamNames}
                      options={teamNamesForSelect}
                      placeholder="Team"
                    />
                  </div>

                  <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 Type"
                    />
                  </div>

                  {/* Date Range Picker */}
                  <div className="flex w-2/5 flex-col">
                    <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"
                  >
                    Reset
                  </button>
                </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="divide-y divide-[#9ca3ae80] bg-meta-4">
                <tr>
                  {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>
                        );
                      }
                    }
                    if (
                      column.accessor === "payment_status" &&
                      parseInt(SubscriptionType) === 1
                    ) {
                      return null;
                    }
                    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) => (
                    <MemberProjectRow
                      key={i}
                      indexe={i}
                      row={row}
                      setSelectedProjectIdForEdit={
                        handleSelectedProjectIdForEdit
                      }
                      setUnSelectedProjectIdForEdit={
                        handleUnSelectedProjectIdForEdit
                      }
                      isEdit={isEditPayment}
                      selectedProjectIdsForEdit={selectedProjectIdsForEdit}
                      columns={columns}
                      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;
