import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import MasterProjectTableBody from "Components/MasterProject/MasterProjectTableBody";
import { getAllClientAPI } from "Src/services/clientService";
import { getAllEmployeeByGroupAPI } from "Src/services/employeeService";
import {
  getAllMasterProjectsAPI,
  resetSubProjectEmployeeAPI,
  updateSubProjectDetailsAPI,
  updateSubProjectEightCountAPI,
  updateSubProjectEmployeeAPI,
  updateSubProjectEmployeeCostAPI,
} from "Src/services/projectService";
import moment from "moment";
import React, {
  memo,
  useCallback,
  useMemo,
  useRef,
  useState,
  useEffect,
} from "react";
import { AuthContext, tokenExpireError } from "../authContext";
import { GlobalContext, showToast } from "../globalContext";

import FormMultiSelect from "Components/FormMultiSelect";
import "Src/index.css";
import { DateRangePicker } from "react-dates";
import "react-dates/initialize";
import "react-dates/lib/css/_datepicker.css";
import { ClipLoader } from "react-spinners";
import CustomSelect2 from "Components/CustomSelect2";

const columns = [
  {
    header: "Mix Date",
    accessor: "mix_date",
    isSorted: false,
    isSortedDesc: false,
    mappingExist: false,
    mappings: {},
  },
  {
    header: "Name",
    accessor: "name",
    isSorted: false,
    isSortedDesc: false,
    mappingExist: false,
    mappings: {},
  },
  {
    header: "Type",
    accessor: "type_name",
    isSorted: false,
    isSortedDesc: false,
    mappingExist: false,
    mappings: {},
  },
  {
    header: "Producer",
    accessor: "member_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: "Add Idea",
    accessor: "idea",
    isSorted: false,
    isSortedDesc: false,
    mappingExist: false,
    mappings: {},
  },
  {
    header: "# of 8cts",
    accessor: "eight_count",
    isSorted: false,
    isSortedDesc: false,
    mappingExist: false,
    mappings: {},
  },
  {
    header: "Writer",
    accessor: "writer",
    isSorted: false,
    isSortedDesc: false,
    mappingExist: false,
    mappings: {},
  },
  {
    header: "Cost",
    accessor: "writer_cost",
    isSorted: false,
    isSortedDesc: false,
    mappingExist: false,
    mappings: {},
  },
  {
    header: "Artist",
    accessor: "artist",
    isSorted: false,
    isSortedDesc: false,
    mappingExist: false,
    mappings: {},
  },
  {
    header: "Cost",
    accessor: "artist_cost",
    isSorted: false,
    isSortedDesc: false,
    mappingExist: false,
    mappings: {},
  },
  {
    header: "Total",
    accessor: "total_cost",
    isSorted: false,
    isSortedDesc: false,
    mappingExist: false,
    mappings: {},
  },
  {
    header: "Status",
    accessor: "status",
    isSorted: false,
    isSortedDesc: false,
    mappingExist: true,
    mappings: {
      1: "Writer",
      2: "Artist",
      3: "Engineer",
      4: "Rejected",
      5: "Completed",
      6: "Inactive",
    },
  },
];

const statusMapping = [
  {
    id: 1,
    name: "Writer",
  },
  {
    id: 2,
    name: "Artist",
  },
  {
    id: 3,
    name: "Engineer",
  },
  {
    id: 4,
    name: "Rejected",
  },
  {
    id: 5,
    name: "Completed",
  },
  {
    id: 6,
    name: "Inactive",
  },
];

const useDebounce = (callback, delay) => {
  const timeoutRef = useRef(null);

  return useCallback(
    (...args) => {
      if (timeoutRef.current) {
        clearTimeout(timeoutRef.current);
      }

      timeoutRef.current = setTimeout(() => {
        callback(...args);
      }, delay);
    },
    [callback, delay]
  );
};

const createLookupMap = (array, key = "id") => {
  return new Map(array.map((item) => [item[key], item]));
};

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

  const [isLoading, setIsLoading] = React.useState(false);
  const [writers, setWriters] = React.useState([]);
  const [artists, setArtists] = React.useState([]);
  const [engineers, setEngineers] = React.useState([]);
  const [producers, setProducers] = React.useState([]);
  const [focusedInput, setFocusedInput] = React.useState(false);

  const [writersForSelect, setWritersForSelect] = React.useState([]);
  const [selectedWriterIds, setSelectedWriterIds] = React.useState([]);
  const [artistsForSelect, setArtistsForSelect] = React.useState([]);
  const [selectedArtistIds, setSelectedArtistIds] = React.useState([]);
  const [engineersForSelect, setEngineersForSelect] = React.useState([]);

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

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

  const [currentTableData, setCurrentTableData] = React.useState([]);
  const [filteredData, setFilteredData] = React.useState([]);

  const [filterUpdated, setFilterUpdated] = React.useState(false);
  const [mixDateFrom, setMixDateFrom] = React.useState("");
  const [mixDateTo, setMixDateTo] = React.useState("");
  const [selectedType, setSelectedType] = React.useState("");

  const [thisWeekSelected, setThisWeekSelected] = React.useState(false);
  const [mixTypesForSelect, setMixTypesForSelect] = React.useState([]);

  const [selectedMixTypeIds, setSelectedMixTypeIds] = React.useState([]);
  const [selectedTeamTypeIds, setSelectedTeamTypeIds] = React.useState([]);

  const [filters, setFilters] = React.useState({
    client_ids: null,
    team_names: null,
    type: null,
    writer_ids: null,
    artist_ids: null,
    engineer_ids: null,
    mix_date_from: null,
    mix_date_to: null,
    team_type: null,
    mix_type_ids: null,
  });

  const [filterPersist, setFilterPersist] = React.useState(false);
  const [reFilter, setReFilter] = React.useState(false);

  const [writersMap, setWritersMap] = useState(new Map());
  const [artistsMap, setArtistsMap] = useState(new Map());
  const [engineersMap, setEngineersMap] = useState(new Map());

  const selectClientRef = useRef(null);
  const selectTeamRef = useRef(null);
  const selectMixTypeRef = useRef(null);
  const selectWriterRef = useRef(null);
  const selectArtistRef = useRef(null);

  const Teamtypes = [
    { id: 1, value: "All Girl" },
    { id: 2, value: "Co-ed" },
    { id: 3, value: "TBD" },
  ];

  React.useEffect(() => {
    const retrievedFilterPersist = JSON.parse(
      localStorage.getItem("filter_masterProject")
    );

    if (retrievedFilterPersist) {
      setFilterPersist(true);
      setFilters((prevFilters) => ({
        ...prevFilters,
        ...retrievedFilterPersist,
      }));

      if (
        retrievedFilterPersist?.team_names &&
        retrievedFilterPersist.team_names.length > 0
      ) {
        setSelectedTeamNames(retrievedFilterPersist.team_names);
      }
      if (
        retrievedFilterPersist?.client_ids &&
        retrievedFilterPersist.client_ids.length > 0
      ) {
        setSelectedClientIds(retrievedFilterPersist.client_ids);
      }
      if (
        retrievedFilterPersist?.writer_ids &&
        retrievedFilterPersist.writer_ids.length > 0
      ) {
        setSelectedWriterIds(retrievedFilterPersist.writer_ids);
      }
      if (
        retrievedFilterPersist?.artist_ids &&
        retrievedFilterPersist.artist_ids.length > 0
      ) {
        setSelectedArtistIds(retrievedFilterPersist.artist_ids);
      }
      if (retrievedFilterPersist?.mix_date_to) {
        setMixDateTo(retrievedFilterPersist?.mix_date_to);
      }
      if (retrievedFilterPersist?.mix_date_from) {
        setMixDateFrom(retrievedFilterPersist?.mix_date_from);
      }
      if (retrievedFilterPersist?.type) {
        setSelectedType(retrievedFilterPersist?.type);
      }
    }
  }, []);

  React.useEffect(() => {
    handleFilterData();
  }, [reFilter]);

  React.useEffect(() => {
    localStorage.setItem("filter_masterProject", JSON.stringify(filters));
  }, [filters]);

  React.useEffect(() => {
    if (filterPersist === true) {
      handleFilterData();
    }
  }, [filterPersist, currentTableData]);

  React.useEffect(() => {
    const today = moment();
    const first = today.clone().startOf("week");
    const last = today.clone().endOf("week");
    const firstDayOfWeek = first.format("YYYY-MM-DD");
    const lastDayOfWeek = last.format("YYYY-MM-DD");
    if (firstDayOfWeek !== mixDateFrom || lastDayOfWeek !== mixDateTo) {
      setThisWeekSelected(false);
    }
  }, [mixDateFrom, mixDateTo]);

  const getUpdatedMasterProjects = async () => {
    try {
      const result = await getAllMasterProjectsAPI();
      if (!result.error) {
        result.list.sort((a, b) => {
          return moment(a.mix_date).diff(moment(b.mix_date));
        });

        let rows = result.list;

        setCurrentTableData(rows);
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  const getAllMasterProjects = async () => {
    try {
      const result = await getAllMasterProjectsAPI();
      if (!result.error) {
        result.list.sort((a, b) => {
          return moment(a.mix_date).diff(moment(b.mix_date));
        });

        let rows = result.list;

        setCurrentTableData(rows);
        setFilteredData(rows);

        // each row has team_name
        let teamNames = [];
        let teamNamesForSelect = [];
        if (rows.length > 0) {
          rows.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);
      } else {
        showToast(globalDispatch, result.message, 5000, "error");
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  const getAllEmployeeByGroup = async () => {
    try {
      const result = await getAllEmployeeByGroupAPI();
      if (!result.error) {
        let writers = result.list.writers;
        let artists = result.list.artists;
        let engineers = result.list.engineers;
        let producers = result.list.producers;

        // sort by alphabetical order
        if (writers.length > 0) {
          writers = writers.sort((a, b) => {
            return a.name.localeCompare(b.name);
          });
        }
        if (artists.length > 0) {
          artists = artists.sort((a, b) => {
            return a.name.localeCompare(b.name);
          });
        }
        if (engineers.length > 0) {
          engineers = engineers.sort((a, b) => {
            return a.name.localeCompare(b.name);
          });
        }
        if (producers.length > 0) {
          producers = producers.sort((a, b) => {
            return a.name.localeCompare(b.name);
          });
        }

        setWriters(writers);
        setArtists(artists);
        setEngineers(engineers);
        setProducers(producers);

        let writersForSelect = [];
        let artistsForSelect = [];
        let engineersForSelect = [];
        let producersForSelect = [];

        if (writers.length > 0) {
          writers.map((row, i) => {
            writersForSelect.push({
              value: row.id,
              label: row.name,
            });
          });
        }

        if (artists.length > 0) {
          artists.map((row, i) => {
            artistsForSelect.push({
              value: row.id,
              label: row.name,
            });
          });
        }

        if (engineers.length > 0) {
          engineers.map((row, i) => {
            engineersForSelect.push({
              value: row.id,
              label: row.name,
            });
          });
        }

        if (producers.length > 0) {
          producers.map((row, i) => {
            producersForSelect.push({
              value: row.id,
              label: row.name,
            });
          });
        }

        setWritersForSelect(writersForSelect);
        setArtistsForSelect(artistsForSelect);
        setEngineersForSelect(engineersForSelect);
      } else {
        setWriters([]);
        setArtists([]);
        setEngineers([]);
        setProducers([]);
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  const handleWriterChange = async (data) => {
    try {
      const result = await updateSubProjectEmployeeAPI(data);
      if (!result.error) {
        await getUpdatedMasterProjects();

        showToast(globalDispatch, result.message, 2000);
        setReFilter(!reFilter);
      } else {
        showToast(globalDispatch, result.message, 2000, "error");
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  const handleWriterCostChange = async (data) => {
    try {
      const result = await updateSubProjectEmployeeCostAPI(data);
      if (!result.error) {
        await getUpdatedMasterProjects();

        showToast(globalDispatch, result.message, 2000);
      } else {
        showToast(globalDispatch, result.message, 2000, "error");
        return;
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  const handleArtistChange = async (data, id, setSelectedArtistId) => {
    try {
      const result = await updateSubProjectEmployeeAPI(data);
      if (!result.error) {
        await getUpdatedMasterProjects();

        showToast(globalDispatch, result.message, 2000);
        setReFilter(!reFilter);
      } else {
        showToast(globalDispatch, result.message, 2000, "error");
        return;
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  const handleArtistCostChange = async (data) => {
    try {
      const result = await updateSubProjectEmployeeCostAPI(data);
      if (!result.error) {
        showToast(globalDispatch, result.message, 2000);
      } else {
        showToast(globalDispatch, result.message, 2000, "error");
        return;
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  const handleEightCountChange = async (data) => {
    try {
      const result = await updateSubProjectEightCountAPI(data);
      if (!result.error) {
        showToast(globalDispatch, result.message, 2000);
        await getAllMasterProjects();
        return;
      } else {
        showToast(globalDispatch, result.message, 2000, "error");
        return;
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  const handleSelectedClientIds = (ids) => {
    if (ids.length === 0) {
      setSelectedClientIds([]);
      setFilters({
        ...filters,
        client_ids: null,
      });

      setReFilter(!reFilter);
    }
    setSelectedClientIds(ids);

    setFilters({
      ...filters,
      client_ids: ids,
    });
  };

  const handleSelectedTeamNames = (names) => {
    if (names.length === 0) {
      setSelectedTeamNames([]);
      setFilters({
        ...filters,
        team_names: null,
      });

      setReFilter(!reFilter);
    }
    setSelectedTeamNames(names);
    setFilters({
      ...filters,
      team_names: names,
    });
  };

  const handleSelectedWriters = (ids) => {
    if (ids && ids.length > 0) {
      setSelectedWriterIds(ids);
      setFilters({
        ...filters,
        writer_ids: ids,
      });
    } else {
      setSelectedWriterIds([]);

      setFilters({
        ...filters,
        writer_ids: null,
      });

      setReFilter(!reFilter);
    }
  };

  const handleSelectedArtists = (row) => {
    if (row && row.length > 0) {
      setSelectedArtistIds(row);

      setFilters({
        ...filters,
        artist_ids: row,
      });
    } else {
      setSelectedArtistIds([]);
      setFilters({
        ...filters,
        artist_ids: null,
      });

      setReFilter(!reFilter);
    }
  };

  const handleFilterData = () => {
    const filtered = getFilteredData(currentTableData);
    setFilteredData(filtered);
    setFilterUpdated(true);
  };

  const getFilteredData = useMemo(() => {
    return (data, filterOverrides = null) => {
      if (!data.length) return [];
      let localFilteredData = data;

      // Use provided filters or fall back to state
      const activeFilters = filterOverrides || filters;

      // Filter by date range
      if (activeFilters.mix_date_from && activeFilters.mix_date_to) {
        const fromDate = moment(activeFilters.mix_date_from).startOf("day");
        const toDate = moment(activeFilters.mix_date_to).startOf("day");
        localFilteredData = localFilteredData.filter((item) => {
          const mixDate = moment(item.mix_date).startOf("day");
          return mixDate.isBetween(fromDate, toDate, "day", "[]");
        });
      }

      // Filter by client IDs
      if (activeFilters.client_ids?.length) {
        const clientIdSet = new Set(
          activeFilters.client_ids.map((c) => c.value)
        );
        localFilteredData = localFilteredData.filter((row) =>
          clientIdSet.has(row.client_id)
        );
      }

      // Filter by team type
      if (activeFilters.team_type) {
        const teamType = Number(activeFilters.team_type);
        localFilteredData = localFilteredData.filter(
          (row) => row.team_type === teamType
        );
      }

      // Filter by mix type IDs
      if (activeFilters.mix_type_ids?.length) {
        const mixTypeIdSet = new Set(
          activeFilters.mix_type_ids.map((m) => m.value)
        );
        localFilteredData = localFilteredData.filter((row) =>
          mixTypeIdSet.has(row.mix_type_id)
        );
      }

      // Filter by team names
      if (activeFilters.team_names?.length) {
        const teamNameSet = new Set(
          activeFilters.team_names.map((t) => t.label)
        );
        localFilteredData = localFilteredData.filter((row) =>
          teamNameSet.has(row.team_name)
        );
      }

      // Filter by type
      if (activeFilters.type) {
        localFilteredData = localFilteredData.reduce((acc, row) => {
          const filteredSubprojects = row.subprojects.filter((subProject) => {
            const subProjectType = subProject.type.replace(/[0-9\s]/g, "");
            return (
              (subProject.is_song && activeFilters.type === "song") ||
              (!subProject.is_song &&
                subProjectType === "Voiceover" &&
                activeFilters.type === "voiceover") ||
              (!subProject.is_song &&
                subProjectType === "Upload" &&
                activeFilters.type === "upload")
            );
          });

          if (filteredSubprojects.length) {
            acc.push({ ...row, subprojects: filteredSubprojects });
          }
          return acc;
        }, []);
      }

      // Employee filters (writers/artists)
      if (
        activeFilters.writer_ids?.length ||
        activeFilters.artist_ids?.length
      ) {
        localFilteredData = localFilteredData.reduce((acc, mainRow) => {
          const filteredSubprojects = mainRow.subprojects.filter((subproject) =>
            subproject.employees.some(
              (employee) =>
                (activeFilters.writer_ids?.some(
                  (person) => person.value === employee.employee_id
                ) &&
                  employee.employee_type === "writer") ||
                (activeFilters.artist_ids?.some(
                  (person) => person.value === employee.employee_id
                ) &&
                  employee.employee_type === "artist")
            )
          );

          if (filteredSubprojects.length > 0) {
            acc.push({ ...mainRow, subprojects: filteredSubprojects });
          }
          return acc;
        }, []);
      }

      return localFilteredData;
    };
  }, [filters]);

  const handleThisWeekFilter = async (e) => {
    e.preventDefault();
    setThisWeekSelected(true);
    const today = moment();
    const first = today.clone().startOf("week");
    const last = today.clone().endOf("week");
    const firstDayOfWeek = first.format("YYYY-MM-DD");
    const lastDayOfWeek = last.format("YYYY-MM-DD");

    setMixDateFrom(firstDayOfWeek);
    setMixDateTo(lastDayOfWeek);
    setFilters({
      ...filters,
      mix_date_from: firstDayOfWeek,
      mix_date_to: lastDayOfWeek,
    });

    setReFilter(!reFilter);
    setFilteredData(filteredData);
    setFilterUpdated(true);
  };

  const resetForm = async () => {
    let confirm = window.confirm("Are you sure you want to reset?");
    if (confirm) {
      localStorage.removeItem("filter_masterProject");
      window.location.reload();
    }
  };

  const getAllClients = async () => {
    try {
      const result = await getAllClientAPI();
      if (!result.error) {
        let forSelect = [];

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

  const handleReset = () => {
    setSelectedClientIds([]);
    setSelectedTeamNames([]);
    setSelectedMixTypeIds([]);
    setSelectedType("");
    setSelectedTeamTypeIds("");
    setThisWeekSelected(false);
    setMixDateFrom("");
    setMixDateTo("");
    setSelectedWriterIds([]);
    setSelectedArtistIds([]);
    setFilters({});
    setFilteredData(currentTableData);
    setFilterUpdated(true);
  };

  const handleSelectedMixTypeIds = (ids) => {
    if (ids.length === 0) {
      setSelectedMixTypeIds([]);
      setFilters((prev) => ({
        ...prev,
        mix_type_ids: null,
      }));
    }
    setSelectedMixTypeIds(ids);
    setFilters((prev) => ({
      ...prev,
      mix_type_ids: ids,
    }));
  };

  const updateSubProject = async (payload) => {
    try {
      const result = await updateSubProjectDetailsAPI(payload);
      if (!result.error) {
        showToast(globalDispatch, result.message, 5000);
        await getUpdatedMasterProjects();
        setReFilter(!reFilter);
      } else {
        showToast(globalDispatch, result.message, 5000, "error");
        return;
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  const handleResetEmployee = async (data) => {
    try {
      const result = await resetSubProjectEmployeeAPI(data);
      if (!result.error) {
        await getAllMasterProjects();
        return showToast(globalDispatch, result.message, 2000);
      } else {
        showToast(globalDispatch, result.message, 2000, "error");
        return;
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

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

    (async function () {
      setIsLoading(true);

      await getAllMasterProjects();

      await getAllEmployeeByGroup();

      await getAllClients();

      setIsLoading(false);
    })();
  }, []);

  return (
    <>
      <div className="max-w-screen mx-auto p-4 md:p-6 2xl:p-10">
        {/* Header Section */}
        <div className="shadow-default bg-boxdark">
          <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-3 text-2xl font-semibold text-white dark:text-white">
                Master Project Search
              </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={handleThisWeekFilter}
                >
                  <FontAwesomeIcon icon={"calendar-days"} />
                  <span
                    className={thisWeekSelected ? "text-primary underline" : ""}
                  >
                    This week
                  </span>
                </span>
              </div>
            </div>
          </div>

          <div className="project_search mb-4 border-b border-strokedark px-4 py-6 sm:px-6 2xl:px-9">
            <div>
              <div className="flex flex-wrap gap-3">
                <div className="flex w-full flex-col md:w-[19%]">
                  <label className="mb-1.5 text-sm font-medium text-white">
                    Program
                  </label>
                  <FormMultiSelect
                    selectRef={selectClientRef}
                    values={selectedClientIds}
                    onValuesChange={handleSelectedClientIds}
                    options={clientsForSelect}
                    placeholder="Programs"
                  />
                </div>

                <div className="flex w-full flex-col md:w-[19%]">
                  <label className="mb-1.5 text-sm font-medium text-white">
                    Team
                  </label>
                  <FormMultiSelect
                    selectRef={selectTeamRef}
                    values={selectedTeamNames}
                    onValuesChange={handleSelectedTeamNames}
                    options={teamNamesForSelect}
                    placeholder="Teams"
                  />
                </div>

                <div className="flex w-full flex-col md:w-[19%]">
                  <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>

                <div className="flex w-full flex-col md:w-[19%]">
                  <label className="mb-1.5 text-sm font-medium text-white">
                    Type
                  </label>
                  <CustomSelect2
                    value={selectedType}
                    onChange={(value) => {
                      setSelectedType(value);
                      setFilters((prev) => ({
                        ...prev,
                        type: value || null,
                      }));
                    }}
                    className="h-[36px] w-full rounded border border-form-strokedark bg-form-input px-3 py-2 text-sm outline-none focus:border-primary"
                  >
                    <option value="">Select Type</option>
                    <option value="voiceover">Voiceover</option>
                    <option value="song">Song</option>
                    <option value="upload">Upload</option>
                  </CustomSelect2>
                </div>

                <div className="flex w-full flex-col md:w-[19%]">
                  <label className="mb-1.5 text-sm font-medium text-white">
                    Team Type
                  </label>
                  <CustomSelect2
                    value={selectedTeamTypeIds}
                    onChange={(value) => {
                      setSelectedTeamTypeIds(value);
                      setFilters((prev) => ({
                        ...prev,
                        team_type: value || null,
                      }));
                    }}
                    className="h-[36px] w-full rounded border border-form-strokedark bg-form-input px-3 py-2 text-sm outline-none focus:border-primary"
                  >
                    <option value="">Select Team Type</option>
                    {Teamtypes.map((row, i) => (
                      <option key={i} value={row.id}>
                        {row.value}
                      </option>
                    ))}
                  </CustomSelect2>
                </div>

                <div className="flex w-full flex-col md:w-[19%]">
                  <label className="mb-1.5 text-sm font-medium text-white">
                    Writer
                  </label>
                  <FormMultiSelect
                    selectRef={selectWriterRef}
                    values={selectedWriterIds}
                    onValuesChange={handleSelectedWriters}
                    options={writersForSelect}
                    placeholder="Writers"
                  />
                </div>

                <div className="flex flex-col md:w-[19%]">
                  <label className="mb-1.5 text-sm font-medium text-white">
                    Artist
                  </label>
                  <FormMultiSelect
                    selectRef={selectArtistRef}
                    values={selectedArtistIds}
                    onValuesChange={handleSelectedArtists}
                    options={artistsForSelect}
                    placeholder="Artists"
                  />
                </div>

                <div className="mb-4 w-full md:w-[39%]">
                  <div className="flex items-center gap-[20px]">
                    <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 }) => {
                      setMixDateFrom(startDate);
                      setMixDateTo(endDate);

                      setFilters({
                        ...filters,
                        mix_date_from: startDate,
                        mix_date_to: endDate,
                      });
                    }}
                    startDate={mixDateFrom ? moment(mixDateFrom) : ""}
                    endDateId="mix_date_end"
                    endDate={mixDateTo ? moment(mixDateTo) : ""}
                    startDateId="mix_date_start"
                  />
                </div>
              </div>
            </div>

            <div className="flex items-end gap-3">
              <button
                type="button"
                className="inline-flex h-[36px] items-center justify-center rounded-md bg-primary px-6 py-2.5 text-center font-medium text-white hover:bg-opacity-90"
                onClick={handleFilterData}
              >
                Search
              </button>

              <button
                type="button"
                className="inline-flex h-[36px] items-center justify-center rounded-md bg-danger px-6 py-2.5 text-center font-medium text-white hover:bg-opacity-90"
                onClick={resetForm}
              >
                Reset
              </button>
            </div>
          </div>

          {/* Table Section */}
          <div className="custom-overflow min-h-[200px] w-full overflow-x-auto pb-4 pt-6 md:pb-6 2xl:pb-10">
            <table className="w-full table-auto">
              <thead className="bg-meta-4">
                <tr>
                  {columns.map((column, i) => (
                    <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 ? (
                <tbody>
                  {filteredData.map((row, i) => (
                    <MasterProjectTableBody
                      key={row.id}
                      getUpdatedMasterProjects={getUpdatedMasterProjects}
                      setUpdateSubprojectPayload={updateSubProject}
                      authState={authState}
                      project={row}
                      statusMapping={statusMapping}
                      columns={columns}
                      filterUpdated={filterUpdated}
                      writers={writers}
                      artists={artists}
                      engineers={engineers}
                      setReFilter={setReFilter}
                      producers={producers}
                      setWriterPayload={handleWriterChange}
                      setArtistPayload={handleArtistChange}
                      setWriterCostPayload={handleWriterCostChange}
                      setArtistCostPayload={handleArtistCostChange}
                      setEightCountPayload={handleEightCountChange}
                      setResetWriterPayload={handleResetEmployee}
                      setResetArtistPayload={handleResetEmployee}
                    />
                  ))}
                </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 Subprojects...
                      </span>
                    </td>
                  </tr>
                </tbody>
              ) : isLoading && currentTableData.length > 0 ? (
                <tbody>
                  <tr>
                    <td colSpan="100%" className="text-center"></td>
                  </tr>
                </tbody>
              ) : (
                <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">
                        No data found
                      </span>
                    </td>
                  </tr>
                </tbody>
              )}
            </table>
          </div>
        </div>
      </div>
    </>
  );
};

export default memo(AdminMasterProjectPage);
