import React, { useRef, useState } from "react";
import { useForm } from "react-hook-form";
import { useNavigate } from "react-router-dom";
import { yupResolver } from "@hookform/resolvers/yup";
import Select from "react-select";
import * as yup from "yup";
import moment from "moment";
import { AuthContext, tokenExpireError } from "Src/authContext";
import { GlobalContext, showToast } from "Src/globalContext";
import {
  getNonNullValue,
  calculateManagementDiscount,
  calculateNetTotal,
  removeKeysWhenValueIsNull,
  sortSeasonAsc,
} from "Utils/utils";
import PaginationBar from "Components/PaginationBar";
import AddButton from "Components/AddButton";
import {
  getAllProjectAPI,
  retrieveAllProjectWithMultiFiltersAPI,
  updateProjectAPI,
} from "Src/services/projectService";
import {
  getAllClientAPI,
  getAllClientsAPI,
  getAllClientsFilterAdminAPI,
} from "Src/services/clientService";
import { getAllMixTypeAPI } from "Src/services/mixTypeServices";
import { retrieveAllSettingsAPI } from "Src/services/settingService";
import Spinner from "Components/Spinner";
import { retrieveAllProjectAdminAPI } from "Src/services/adminServices";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { sendEmailAPIV3 } from "Src/services/emailService";
import {
  addMediaAPI,
  retrieveAllMediaAPI,
} from "Src/services/clientProjectDetailsService";
import { uploadS3FilesAPI } from "Src/services/workOrderService";
import jsPDF from "jspdf";
import html2canvas from "html2canvas";
import { retrieveAllMixSeasonsAPI } from "Src/services/mixSeasonService";
import AdminProjectRow from "Components/AdminListProjectRow";
import License from "Components/License";
import { DateRangePicker } from "react-dates";
import { ClipLoader } from "react-spinners";
import FormMultiSelect from "Components/FormMultiSelect";
import CustomSelect2 from "Components/CustomSelect2";

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: "user_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 AdminListProjectPage = () => {
  const { dispatch, state: authState } = React.useContext(AuthContext);
  const { dispatch: globalDispatch } = React.useContext(GlobalContext);

  const [isLoading, setIsLoading] = React.useState(false);

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

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

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

  const [settings, setSettings] = React.useState([]);
  const [currentTableData, setCurrentTableData] = React.useState([]);
  // const [pageSize, setPageSize] = React.useState(10);
  const [pageCount, setPageCount] = React.useState(0);
  const [dataTotal, setDataTotal] = React.useState(0);
  const [currentPage, setPage] = React.useState(0);
  const [filterStart, setFilterStart] = useState(false);
  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 [cachedProjectMixDateStart, setCachedProjectMixDateStart] =
    React.useState("");
  const [CompleteCount, setCompleteCount] = React.useState(0);
  const [UnfilteredTotalCount, setUnfilteredTotalCount] = React.useState(0);
  const [cachedProjectMixDateEnd, setCachedProjectMixDateEnd] =
    React.useState("");
  const [selectedProjectIdsForEdit, setSelectedProjectIdsForEdit] =
    React.useState([]);
  const [mixSeasons, setMixSeasons] = React.useState([]);
  const [isEditPayment, setIsEditPayment] = React.useState(false);
  const [HidecompletedStatus, setHideCompletedStatus] = React.useState(false);
  const [focusedInput, setFocusedInput] = React.useState(null);
  const [paymentStatus, setPaymentStatus] = React.useState(null);
  const [thisWeekSelected, setThisWeekSelected] = React.useState(false);

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

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

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

  React.useEffect(() => {
    let projectClientId =
      localStorage.getItem("AdminProjectClientId") &&
      JSON.parse(localStorage.getItem("AdminProjectClientId"));
    let projectTeamName =
      localStorage.getItem("AdminProjectTeamName") &&
      JSON.parse(localStorage.getItem("AdminProjectTeamName"));
    let projectMixTypeId =
      localStorage.getItem("AdminProjectMixTypeId") &&
      JSON.parse(localStorage.getItem("AdminProjectMixTypeId"));
    let projectMixDateStart = localStorage.getItem("AdminProjectMixDateStart");
    let projectMixDateEnd = localStorage.getItem("AdminProjectMixDateEnd");

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

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

      let projectClientId =
        localStorage.getItem("AdminProjectClientId") &&
        JSON.parse(localStorage.getItem("AdminProjectClientId"));
      let projectTeamName =
        localStorage.getItem("AdminProjectTeamName") &&
        JSON.parse(localStorage.getItem("AdminProjectTeamName"));
      let projectMixTypeId =
        localStorage.getItem("AdminProjectMixTypeId") &&
        JSON.parse(localStorage.getItem("AdminProjectMixTypeId"));
      let projectMixDateStart = localStorage.getItem(
        "AdminProjectMixDateStart"
      );
      let projectMixDateEnd = localStorage.getItem("AdminProjectMixDateEnd");

      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 && 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 || null,
          mix_date_end: projectMixDateEnd || null,
        };

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

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

  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}`);
      console.log(input);
      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);
    }
  };

  function ShowCompletedProjects(status) {
    (async function () {
      setIsLoading(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)
            );
            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);
    })();
  }

  const navigate = useNavigate();

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

  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("AdminProjectClientId") &&
        JSON.parse(localStorage.getItem("AdminProjectClientId"));
      let projectTeamName =
        localStorage.getItem("AdminProjectTeamName") &&
        JSON.parse(localStorage.getItem("AdminProjectTeamName"));
      let projectMixTypeId =
        localStorage.getItem("AdminProjectMixTypeId") &&
        JSON.parse(localStorage.getItem("AdminProjectMixTypeId"));
      let projectMixDateStart = localStorage.getItem(
        "AdminProjectMixDateStart"
      );
      let projectMixDateEnd = localStorage.getItem("AdminProjectMixDateEnd");

      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 && 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 || null,
          mix_date_end: projectMixDateEnd || null,
        };
        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("AdminProjectPageSize", limit);
  }

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

      let projectClientId =
        localStorage.getItem("AdminProjectClientId") &&
        JSON.parse(localStorage.getItem("AdminProjectClientId"));
      let projectTeamName =
        localStorage.getItem("AdminProjectTeamName") &&
        JSON.parse(localStorage.getItem("AdminProjectTeamName"));
      let projectMixTypeId =
        localStorage.getItem("AdminProjectMixTypeId") &&
        JSON.parse(localStorage.getItem("AdminProjectMixTypeId"));
      let projectMixDateStart = localStorage.getItem(
        "AdminProjectMixDateStart"
      );
      let projectMixDateEnd = localStorage.getItem("AdminProjectMixDateEnd");

      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 && 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 || null,
          mix_date_end: projectMixDateEnd || null,
        };
        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("AdminProjectClientId") &&
        JSON.parse(localStorage.getItem("AdminProjectClientId"));
      let projectTeamName =
        localStorage.getItem("AdminProjectTeamName") &&
        JSON.parse(localStorage.getItem("AdminProjectTeamName"));
      let projectMixTypeId =
        localStorage.getItem("AdminProjectMixTypeId") &&
        JSON.parse(localStorage.getItem("AdminProjectMixTypeId"));
      let projectMixDateStart = localStorage.getItem(
        "AdminProjectMixDateStart"
      );
      let projectMixDateEnd = localStorage.getItem("AdminProjectMixDateEnd");

      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 && 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 || null,
          mix_date_end: projectMixDateEnd || null,
        };

        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) {
    try {
      setIsLoading(true);
      // const result = await retrieveAllProjectAPI(pageNum, limitNum, filter);
      const result = await retrieveAllProjectAdminAPI(
        pageNum,
        limitNum,
        filter
      );
      const { list, total, limit, num_pages, page } = result;
      console.log(list);
      setCurrentTableData(list);
      setPageSize(limit);
      setPageCount(num_pages);
      setUnfilteredTotalCount(result?.total_count);
      setCompleteCount(result?.total_completed_projects);
      setPage(page);
      setDataTotal(total);
      setCanPreviousPage(page > 1);
      setCanNextPage(page + 1 <= num_pages);
      setIsLoading(false);
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  }

  const resetForm = async () => {
    reset();
    setIsLoading(true);
    localStorage.setItem("AdminProjectClientId", "");
    localStorage.setItem("AdminProjectTeamName", "");
    localStorage.setItem("AdminProjectMixTypeId", "");
    localStorage.setItem("AdminProjectMixDateStart", "");
    localStorage.setItem("AdminProjectMixDateEnd", "");
    localStorage.setItem("AdminProjectPageSize", "");
    setCachedProjectClientId("");
    setSelectedClientIds([]);
    setSelectedTeamNames([]);
    setSelectedMixTypeIds([]);
    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 && 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: mix_date_start || null,
        mix_date_end: mix_date_end || null,
      };

      //

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

      // localStorage.setItem('projectClientId', client_id ?? '');
      // localStorage.setItem('projectTeamName', team_name ?? '');
      // localStorage.setItem('projectMixTypeId', mix_type_id ?? '');
      localStorage.setItem("AdminProjectMixDateStart", mix_date_start ?? "");
      localStorage.setItem("AdminProjectMixDateEnd", 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) => {
    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("AdminProjectMixDateStart", startOfWeek);
      localStorage.setItem("AdminProjectMixDateEnd", endOfWeek);

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

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

  const getAllClients = async () => {
    try {
      const result = await getAllClientsFilterAdminAPI();
      if (!result.error) {
        if (result.list.length > 0) {
          let forSelect = [];
          if (result.list.length > 0) {
            result.list.map((row, i) => {
              forSelect.push({
                value: row.client_id,
                label: row.client_program,
              });
            });
          }

          let list = forSelect.sort((a, b) => {
            if (a.label < b.label) {
              return -1;
            }
            return 1;
          });
          setClientsForSelect(list);
        }
      }
    } 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("AdminProjectMixDateStart", 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("AdminProjectMixDateEnd", e.target.value);
    }
  };

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

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

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

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

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

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

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

    let projectClientId =
      localStorage.getItem("AdminProjectClientId") &&
      JSON.parse(localStorage.getItem("AdminProjectClientId"));
    let projectTeamName =
      localStorage.getItem("AdminProjectTeamName") &&
      JSON.parse(localStorage.getItem("AdminProjectTeamName"));
    let projectMixTypeId =
      localStorage.getItem("AdminProjectMixTypeId") &&
      JSON.parse(localStorage.getItem("AdminProjectMixTypeId"));
    let projectMixDateStart = localStorage.getItem("AdminProjectMixDateStart");
    let projectMixDateEnd = localStorage.getItem("AdminProjectMixDateEnd");

    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 && 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 || null,
        mix_date_end: projectMixDateEnd || null,
      };
      (async function () {
        setIsLoading(true);
        // await retrieveAllSettings();
        await getAllProjects();
        await getAllClients();
        await getAllMixTypes();
        setIsLoading(false);
      })();

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

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

    //
  }, []);

  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 selectClientRef = useRef(null);
  const selectTeamNameRef = useRef(null);
  const selectMixTypeRef = 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>
        </div>

        {/* Main content area with dark background */}
        <div className="shadow-default rounded border-b border-strokedark bg-boxdark px-4 pt-10 sm:px-6 2xl:px-10 dark:border-strokedark dark:bg-boxdark">
          <div className="s flex w-full border-b border-strokedark pb-6">
            <div className="flex w-1/2 flex-row items-end gap-1">
              <h4 className="text-2xl font-medium text-white">Projects /</h4>
              <div className="flex items-center gap-1 text-white">
                <h6>{CompleteCount} Completed /</h6>
                <h6>{UnfilteredTotalCount} Total</h6>
              </div>
              {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
                      name="engineer"
                      value={paymentStatus}
                      onChange={async (value) => {
                        await updateProjectsPaymentStatus(
                          selectedProjectIdsForEdit,
                          value
                        );
                        setPaymentStatus(value);
                      }}
                      label="Payment Status"
                      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"
                    >
                      <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)}
              />
              <button
                className="hover:bg-primary/9 flex items-center justify-center rounded bg-primary px-2 py-1.5 text-sm font-semibold text-white"
                type="button"
                onClick={() => {
                  navigate(`/${authState.role}/master-project-view`);
                }}
              >
                Master Project View
              </button>
            </div>
          </div>
          <div className="">
            {/* Search Filters */}
            <form
              className="mb-6 rounded border-b border-strokedark pb-4"
              onSubmit={handleSubmit(onSubmit)}
            >
              <div className="mt-4 flex flex-wrap gap-4">
                {/* Program Name 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="Programs"
                  />
                </div>

                {/* Team Name Filter */}
                <div className="flex w-1/5 flex-col">
                  <label className="mb-1.5 text-sm font-medium text-white">
                    Team Name
                  </label>
                  <FormMultiSelect
                    selectRef={selectTeamNameRef}
                    values={selectedTeamNames}
                    onValuesChange={handleSelectedTeamNames}
                    options={teamNamesForSelect}
                    placeholder="Team name"
                  />
                </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="flex w-full flex-col md:w-2/6">
                  <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)
                        : ""
                    }
                    endDateId="mix_date_end"
                    endDate={
                      cachedProjectMixDateEnd
                        ? moment(cachedProjectMixDateEnd)
                        : ""
                    }
                    startDateId="mix_date_start"
                  />
                </div>
              </div>

              {/* Search Buttons */}
              <div className="mt-4 flex gap-2">
                <button
                  type="submit"
                  className="inline-flex h-[36px] items-center justify-center rounded-md bg-primary px-4 py-2 text-center 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-center text-sm font-medium text-white hover:bg-opacity-90"
                >
                  Reset
                </button>
              </div>
            </form>

            <div className="mt-4 rounded border-b border-strokedark bg-boxdark">
              <div className="custom-overflow min-h-[150px] max-w-full">
                <table className=" w-full table-auto ">
                  <thead>
                    <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="px-4 py-4 font-medium text-white"
                              >
                                <span>All</span>
                                <input
                                  type="checkbox"
                                  className="ml-2 h-5 w-5 rounded border-2 border-[#9ca3ae80] bg-transparent checked:border-primary checked:bg-primary"
                                  onChange={handleCheckAllChange}
                                />
                                <span>
                                  {column.isSorted
                                    ? column.isSortedDesc
                                      ? " ▼"
                                      : " ▲"
                                    : ""}
                                </span>
                              </th>
                            );
                          } else {
                            return (
                              <th
                                key={i}
                                scope="col"
                                className="border border-[#9ca3ae80] px-4 py-4 font-medium uppercase text-white"
                              >
                                <span>
                                  {column.isSorted
                                    ? column.isSortedDesc
                                      ? " ▼"
                                      : " ▲"
                                    : ""}
                                </span>
                              </th>
                            );
                          }
                        }
                        return (
                          <th
                            key={i}
                            scope="col"
                            className="te whitespace-nowrap  px-4 py-3 text-left text-xs font-medium uppercase text-bodydark1"
                          >
                            {column.header}
                            <span>
                              {column.isSorted
                                ? column.isSortedDesc
                                  ? " ▼"
                                  : " ▲"
                                : ""}
                            </span>
                          </th>
                        );
                      })}
                    </tr>
                  </thead>
                  {!isLoading && currentTableData.length > 0 ? (
                    <tbody className="border-b border-strokedark bg-boxdark">
                      {currentTableData.map((row, i) => (
                        <AdminProjectRow
                          row={row}
                          indexe={i}
                          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>
        </div>
      </div>
    </>
  );
};

export default AdminListProjectPage;
