import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { yupResolver } from "@hookform/resolvers/yup";
import AddSongModal from "Components/AddSongModal";
import CustomSelect2 from "Components/CustomSelect2";
import EditSongModal from "Components/EditSongModal";
import ReassignSongModal from "Components/ReassignSongModal";
import SongTableRow from "Components/Songs/SongTableRow";
import React, { useEffect, useState, useRef, useCallback } from "react";
import { useForm } from "react-hook-form";
import { useNavigate } from "react-router-dom";
import { ClipLoader } from "react-spinners";
import { AuthContext, tokenExpireError } from "Src/authContext";
import { GlobalContext, showToast } from "Src/globalContext";
import { createPopper } from "@popperjs/core";
import { createDownloadProgressBox } from "Utils/downloadProgress";
import {
  getAllEmployeeByGroupAPI,
  getEmployeeDetailsAPI,
} from "Src/services/employeeService";
import { getAllMixSeasonAPI } from "Src/services/mixSeasonService";
import {
  getAllProjectAPI,
  getAllUnAssignedSubSongsAPI,
  reassignSongsAPI,
  updateSubProjectDetailsAPI,
  resetSubProjectEmployeeAPI,
  updateSubProjectEmployeeAPI,
  attachProjectsToSong,
  addAndAssignIdeaAPI,
  assignSubProjectIdeasAPI,
  getAllSubProjectIdeaAPI,
  getAllIdeaAPI,
  addAndAssignIdeaToMultiSubProjectsAPI,
} from "Src/services/projectService";
import MkdSDK from "Utils/MkdSDK";
import {
  removeKeysWhenValueIsNull,
  replaceBrTagToNextLine,
  sortByStringAsc,
  sortSeasonAsc,
} from "Utils/utils";
import * as XLSX from "xlsx-js-style";
import * as yup from "yup";
import JSZip from "jszip";
import jsPDF from "jspdf";
import PaginationBar from "Components/PaginationBar";
import moment from "moment";
import { DateRangePicker, SingleDatePicker } from "react-dates";
import "react-dates/initialize";
import "react-dates/lib/css/_datepicker.css";

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 columns = [
  { accessor: "edit", header: "" },
  { accessor: "select", header: "sel" },
  { accessor: "id_string", header: "ID" },
  { accessor: "mix_date", header: "Mix Date" },
  { accessor: "program_name", header: "Program/Team" },
  { accessor: "actions", header: "Actions" },
  { accessor: "is_writer", header: "Writer" },
  { accessor: "writer_cost", header: "Writer Cost" },
  { accessor: "is_artist", header: "Artist" },
  { accessor: "artist_cost", header: "Artist Cost" },
  { accessor: "is_engineer", header: "Engineer" },
  { accessor: "engineer_cost", header: "Engineer Cost" },
  { accessor: "gender", header: "Gender" },
  { accessor: "type_name", header: "Song Title" },
  { accessor: "song_key", header: "Song Key" },
  { accessor: "bpm", header: "BPM" },
  { accessor: "lyrics", header: "Lyrics" },
  { accessor: "genre", header: "Genre" },
  { accessor: "song_type", header: "Song Type" },
  { accessor: "notes", header: "Notes" },
  { accessor: "assigned_to", header: "Assigned To" },
  { accessor: "status", header: "Status" },
];

const ListUnAssignedSongsPage = () => {
  const navigate = useNavigate();
  const tableContainerRef = useRef(null);

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

  const [showAction, setShowAction] = React.useState(false);
  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(1);
  // Add near other useState hooks
  const [mixDateFilterRange, setMixDateFilterRange] = useState({
    startDate: null,
    endDate: null,
  });
  const [mixDateFilterFocusedInput, setMixDateFilterFocusedInput] =
    useState(null);
  const [canPreviousPage, setCanPreviousPage] = React.useState(false);
  const [canNextPage, setCanNextPage] = React.useState(false);

  const [loading, setLoading] = React.useState(false);

  const [mixSeasons, setMixSeasons] = React.useState([]);
  const [filteredData, setFilteredData] = React.useState([]);
  const [canEdit, setCanEdit] = React.useState(true);

  const [showReassignModal, setShowReassignModal] = React.useState(false);
  const [writers, setWriters] = React.useState([]);
  const [artists, setArtists] = React.useState([]);
  const [engineers, setEngineers] = React.useState([]);
  const [producers, setProducers] = React.useState([]);
  const [projects, setProjects] = React.useState([]);
  const [showFilteredLyrics, setShowFilteredLyrics] = React.useState(false);
  const [filterButtonRefs] = useState({});
  const [popperInstances, setPopperInstances] = useState({});

  const [
    selectedSubProjectIdsForReassign,
    setSelectedSubProjectIdsForReassign,
  ] = React.useState([]);

  const pageSizeFromLocalStorage = localStorage.getItem("SongPageSize");

  const [filters, setFilters] = React.useState({
    mix_season_id: "",
    type_name: "",
    lyrics: "",
  });

  const schema = yup.object({
    name: yup.string(),
    status: yup.string(),
  });

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

  const [showAddSongModal, setShowAddSongModal] = React.useState(false);
  const [isZoomed, setIsZoomed] = useState(false);
  const [zoomLevel, setZoomLevel] = useState(() => {
    const savedZoom = localStorage.getItem("songListZoomLevel");
    return savedZoom ? parseInt(savedZoom) : 100;
  });

  const [columnFilters, setColumnFilters] = useState({});
  const [showFilterMenu, setShowFilterMenu] = useState(null);
  const [filterSearchValues, setFilterSearchValues] = useState({});

  const [showEditSongModal, setShowEditSongModal] = useState(false);
  const [selectedSongForEdit, setSelectedSongForEdit] = useState(null);

  const [showMoveModal, setShowMoveModal] = useState(false);
  const [selectedSongsForMove, setSelectedSongsForMove] = useState([]);
  const [isMoveModeActive, setIsMoveModeActive] = useState(false);
  const [selectedMixSeason, setSelectedMixSeason] = useState("");

  // Add new state for download modal
  const [showDownloadModal, setShowDownloadModal] = useState(false);
  const [downloadFilters, setDownloadFilters] = useState({
    filterType: "all",
    id_range: {
      start: "",
      end: "",
      array: [],
    },
    mix_date_range: {
      start: "",
      end: "",
    },
    writer_id: "",
    artist_id: "",
    engineer_id: "",
  });

  // Add new state for column values
  const [columnValues, setColumnValues] = useState({});

  const [ideas, setIdeas] = useState([]);

  const [lyricsSearch, setLyricsSearch] = useState("");

  // Add new state variables
  const [baseFilters, setBaseFilters] = useState({}); // Stores all possible filter values
  const [activeFilters, setActiveFilters] = useState([]); // Stores current applied filters

  // Add new state for range filters
  const [rangeFilters, setRangeFilters] = useState({
    artist_cost: { min: 0, max: 100 }, // Default range
    writer_cost: { min: 0, max: 100 },
    engineer_cost: { min: 0, max: 100 },
    bpm: { min: 0, max: 200 }, // Default range for BPM
  });

  // Add helper function to determine if column should use range filter
  const isRangeColumn = (accessor) => {
    return ["artist_cost", "writer_cost", "engineer_cost", "bpm"].includes(
      accessor
    );
  };

  const isDateColumn = (accessor) => {
    return accessor === "mix_date";
  };

  const generatePdfBlobCombined = async (lyricsText) => {
    const doc = new jsPDF();
    const pageHeight = doc.internal.pageSize.height;
    const lineHeight = 7; // Adjust this value to change line spacing
    let cursorPosition = 10;

    const addTextToPDF = (text) => {
      const textLines = doc.splitTextToSize(text, 180);
      textLines.forEach((line) => {
        if (cursorPosition > pageHeight - 20) {
          doc.addPage();
          cursorPosition = 10;
        }
        doc.text(line, 10, cursorPosition);
        cursorPosition += lineHeight;
      });
      cursorPosition += lineHeight; // Add extra space between sections
    };
    const sections = lyricsText.split("\n\n");

    sections.forEach((section, index) => {
      if (index > 0 && cursorPosition > pageHeight - 40) {
        doc.addPage();
        cursorPosition = 10;
      }

      const [header, ...content] = section.split("\n");

      // Add header (program, team, type)
      doc.setFontSize(12);
      doc.setFont(undefined, "bold");
      addTextToPDF(header);

      // Add content (lyrics)
      doc.setFontSize(10);
      doc.setFont(undefined, "normal");
      addTextToPDF(content.join("\n"));
    });

    return doc.output("blob");
  };

  // Add this useEffect to handle popper instances cleanup
  useEffect(() => {
    return () => {
      // Cleanup popper instances on unmount
      Object.values(popperInstances).forEach((instance) => instance?.destroy());
    };
  }, [popperInstances]);

  const callDataAgain = (page = currentPage) => {
    (async function () {
      console.log(page, "currentpage");
      await getData(
        page,
        pageSizeFromLocalStorage
          ? Number(pageSizeFromLocalStorage)
          : pageSize || pageSize
      );
      setLoading(false);
      document.getElementById("mainContainer").scrollTo({
        top: 0,
        behavior: "smooth",
      });
    })();
  };

  function updatePageSize(limit) {
    (async function () {
      setLoading(true);
      setPageSize(limit);
      await getData(currentPage, limit);
      setLoading(false);
      document.getElementById("mainContainer").scrollTo({
        top: 0,
        behavior: "smooth",
      });
    })();
    localStorage.setItem("workOrderPageSize", limit);
  }

  function previousPage() {
    (async function () {
      setLoading(true);
      await getData(
        currentPage - 1,
        pageSizeFromLocalStorage ? Number(pageSizeFromLocalStorage) : pageSize
      );
      setLoading(false);
      document.getElementById("mainContainer").scrollTo({
        top: 0,
        behavior: "smooth",
      });
    })();
  }

  function nextPage() {
    (async function () {
      setLoading(true);
      await getData(
        currentPage + 1,
        pageSizeFromLocalStorage
          ? Number(pageSizeFromLocalStorage)
          : pageSize || pageSize
      );
      setLoading(false);
      document.getElementById("mainContainer").scrollTo({
        top: 0,
        behavior: "smooth",
      });
    })();
  }

  async function getData(pageNum, limitNum) {
    try {
      const sdk = new MkdSDK();

      // Process filters to separate employee filters from others
      const employeeFilters = [];
      const regularFilters = [];

      activeFilters.forEach((filter) => {
        if (filter.startsWith("employee_filter:")) {
          // Extract employee filter conditions
          const conditions = JSON.parse(filter.replace("employee_filter:", ""));
          employeeFilters.push(...conditions);
        } else {
          regularFilters.push(filter);
        }
      });

      const payload = removeKeysWhenValueIsNull({
        page: pageNum,
        limit: limitNum,
        filter: regularFilters.length > 0 ? regularFilters : null,
        employee_filter: employeeFilters.length > 0 ? employeeFilters : null,
      });

      const result = await sdk.callRawAPI(
        "/v3/api/custom/equality_record/project/sub_project/type_name",
        payload,
        "POST"
      );

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

      setPageCount(Math.ceil(total / limit));

      setDataTotal(total);
      setCanPreviousPage(page > 1);
      setCanNextPage(page + 1 <= Math.ceil(total / limit));
      setCurrentTableData(list);
      setFilteredData(list);
      setLoading(false);
    } catch (error) {
      setLoading(false);
      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;

        if (writers.length > 0) {
          writers = sortByStringAsc(writers, "name");
        }

        if (artists.length > 0) {
          artists = sortByStringAsc(artists, "name");
        }

        if (engineers.length > 0) {
          engineers = sortByStringAsc(engineers, "name");
        }

        if (producers.length > 0) {
          producers = sortByStringAsc(producers, "name");
        }

        setWriters(writers);
        setArtists(artists);
        setEngineers(engineers);
        setProducers(producers);
      } else {
        setWriters([]);
        setArtists([]);
        setEngineers([]);
        setProducers([]);
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  const resetForm = async () => {
    reset();
    setFilters({
      mix_season_id: "",
      type_name: "",
      lyrics: "",
    });
    setLyricsSearch("");
    // Only clear non-column filters
    console.log(activeFilters, "filters");
    setActiveFilters([]);
    await callDataAgain(currentPage);
    setShowFilteredLyrics(false);
  };

  const handleFilterData = async (e) => {
    e.preventDefault();

    // Get current column filters
    const existingColumnFilters = activeFilters.filter(
      (filter) => filter.includes(" IN ") // Keep all column filters
    );

    // Create new search filters
    const searchFilters = [];

    // Add mix_season filter if selected
    if (filters.mix_season_id) {
      searchFilters.push(`sp.mix_season_id IN (${filters.mix_season_id})`);
    }

    // Add song title filter if entered - using LIKE for partial matches
    if (filters.type_name) {
      searchFilters.push(`type_name LIKE '%${filters.type_name}%'`);
    }

    // Add lyrics filter if entered - using LIKE for partial matches
    if (filters.lyrics) {
      searchFilters.push(`lyrics LIKE '%${filters.lyrics}%'`);
      setShowFilteredLyrics(true);
    } else {
      setShowFilteredLyrics(false);
    }

    // Combine existing column filters with new search filters
    setActiveFilters([...existingColumnFilters, ...searchFilters]);
  };

  const getAllMixSeasons = async () => {
    try {
      const result = await getAllMixSeasonAPI();
      if (!result.error) {
        setMixSeasons(sortSeasonAsc(result.list));
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  const handleEditClick = (e) => {
    e.preventDefault();
    // Get the selected songs data
    const selectedSongs = selectedSubProjectIdsForReassign.map((id) =>
      currentTableData.find((song) => song.id === id)
    );

    setSelectedSongForEdit(selectedSongs[0]);
    setShowEditSongModal(true);
  };

  const handleReassignSong = async (projectId) => {
    try {
      const result = await reassignSongsAPI({
        project_id: projectId,
        subproject_ids: selectedSubProjectIdsForReassign,
      });
      if (!result.error) {
        showToast(globalDispatch, result.message, 5000);
        setShowReassignModal(false);
        setSelectedSubProjectIdsForReassign([]);
        // setSelectedSubProjectIdsForReassign((prevSelectedIds) => []);
        setCanEdit(false);
        await callDataAgain(currentPage);
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  const getAllProjects = async () => {
    try {
      const result = await getAllProjectAPI();
      if (!result.error) {
        setProjects(result.list);
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  const handleCheckBoxChange = (e) => {
    if (e.target.checked) {
      // add to array
      setSelectedSubProjectIdsForReassign((prevSelectedIds) => [
        ...prevSelectedIds,
        Number(e.target.value),
      ]);

      setCanEdit(true);
    } else {
      // remove from array
      setSelectedSubProjectIdsForReassign((prevSelectedIds) =>
        prevSelectedIds.filter(
          (item) => Number(item) !== Number(e.target.value)
        )
      );

      if (selectedSubProjectIdsForReassign.length === 1) {
        setCanEdit(false);
      }
    }
  };

  const handleReassignSongModalClose = (e) => {
    setShowReassignModal(false);
  };

  const handleUpdateSubProjectDetails = async (payload) => {
    try {
      const result = await updateSubProjectDetailsAPI(payload);
      if (!result.error) {
        await callDataAgain(currentPage);
        await refreshFilters();
      } else {
        showToast(globalDispatch, result.message, 5000, "error");
      }
    } catch (error) {
      showToast(globalDispatch, error.message, 5000, "error");
    }
  };

  const renderHighlightedLyrics = (lyrics, searchTerm) => {
    if (!lyrics) return null;

    // Use a regular expression to find and highlight the search term
    const regex = new RegExp(`(${searchTerm})`, "gi");
    const parts = lyrics.split(regex);

    return (
      <>
        {parts.map((part, index) =>
          regex.test(part) ? (
            <span key={index} className="font-bold text-yellow-500">
              {replaceBrTagToNextLine(part)}
            </span>
          ) : (
            <span key={index}>{replaceBrTagToNextLine(part)}</span>
          )
        )}
      </>
    );
  };

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

    (async function () {
      setLoading(true);
      await Promise.all([
        getData(1, pageSize),
        getAllProjects(),
        getAllMixSeasons(),
        fetchAllColumnValues(),
      ]);
      setLoading(false);
    })();
  }, []);
  useEffect(() => {
    if (currentPage && pageSize) {
      getData(currentPage, pageSize);
    }
  }, [activeFilters]); // Re-fetch when filters change

  console.log(mixSeasons, "mixse");

  const handleAddSong = async (e) => {
    try {
      // ... existing add song logic ...
      await getData(currentPage, pageSize);
      await refreshFilters();
    } catch (error) {
      console.error(error);
    }
  };

  // Function to get filter options for a specific column
  const getFilterOptions = (accessor) => {
    // If we have API values, use those
    console.log(columnValues, "columns");
    if (columnValues[accessor]) {
      return columnValues[accessor];
    }

    // Otherwise fall back to unique values from current data
    return getUniqueValues(currentTableData, accessor);
  };

  // Replace the dummy handlers with actual implementations
  const handleAddIdea = async (subProjectId, data) => {
    console.log(data, "projectss");
    try {
      const payload = {
        subproject_id: Number(subProjectId),
        project_id: Number(data.project_id),
        idea_key: data.idea_key,
        idea_value: data.idea_value,
      };
      const result = await addAndAssignIdeaAPI(payload);
      if (!result.error) {
        showToast(globalDispatch, result.message, 5000);
        await callDataAgain(currentPage);
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  const handleAssignIdea = async (subProjectId, ideaIds, projectId) => {
    console.log(projectId, "projectss");
    try {
      const payload = {
        subproject_id: Number(subProjectId),
        idea_ids: ideaIds,
        project_id: projectId,
      };
      const result = await assignSubProjectIdeasAPI(payload);
      if (!result.error) {
        showToast(globalDispatch, result.message, 5000);
        await callDataAgain(currentPage);
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  // Dummy handler functions
  const handleFileUpload = (id) => {
    console.log("Handling file upload for id:", id);
    showToast(globalDispatch, "File upload clicked", 3000);
  };

  const handleUpdateField = async (id, field, value) => {
    try {
      const result = await updateSubProjectDetailsAPI({
        subproject_id: id,
        [field]: value,
      });
      await callDataAgain(currentPage);
    } catch (error) {
      showToast(globalDispatch, error.message, 5000, "error");
    }
  };

  const handleAddIdeaForMultiSubProject = async (data) => {
    try {
      const payload = {
        project_id: Number(data.project_id),
        subproject_ids: data.subproject_ids,
      };
      const result = await addAndAssignIdeaToMultiSubProjectsAPI(payload);
      if (!result.error) {
        showToast(globalDispatch, result.message, 5000);
        await callDataAgain(currentPage);
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  // // Add useEffect for zoom functionality
  // useEffect(() => {
  //   const handleResize = () => {
  //     const zoom = Number((window.innerWidth / window.screen.width).toFixed(3));
  //     const pageContainer = document.getElementById(
  //       "unassigned-songs-container"
  //     );
  //     if (pageContainer) {
  //       pageContainer.style.zoom = zoom;
  //     }
  //   };

  //   // Initial zoom
  //   handleResize();

  //   // Add resize listener
  //   window.addEventListener("resize", handleResize);

  //   // Cleanup
  //   return () => {
  //     window.removeEventListener("resize", handleResize);
  //   };
  // }, []);

  useEffect(() => {
    const handleClickOutside = (event) => {
      // Don't close if clicking inside the DateRangePicker or its portal
      if (
        event.target.closest(".DateRangePicker") ||
        event.target.closest(".DateRangePicker_portal") ||
        event.target.closest(".DayPicker") ||
        event.target.closest(".CalendarDay")
      ) {
        return;
      }

      if (
        filterMenuRef.current &&
        !filterMenuRef.current.contains(event.target)
      ) {
        setShowFilterMenu(null);
      }
    };

    document.addEventListener("mousedown", handleClickOutside);
    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, []);

  const applyZoom = useCallback((level) => {
    console.log("applyZoom called with level:", level);
    console.log("tableContainerRef current:", tableContainerRef.current);

    if (tableContainerRef.current) {
      console.log("Applying zoom style:", `${level / 100}`);
      tableContainerRef.current.style.zoom = level / 100;
    } else {
      console.warn(
        "tableContainerRef.current is null - zoom could not be applied"
      );
    }
  }, []);

  useEffect(() => {
    console.log("Initial zoomLevel from localStorage:", zoomLevel);
    applyZoom(zoomLevel);
  }, [zoomLevel, applyZoom]);

  // Add a new useEffect to check when the ref is available
  useEffect(() => {
    console.log("Component mounted, checking ref:", tableContainerRef.current);
    if (tableContainerRef.current) {
      console.log("Ref is available on mount, applying zoom:", zoomLevel);
      applyZoom(zoomLevel);
    }
  }, []);

  const handleZoom = (direction) => {
    console.log("handleZoom called with direction:", direction);
    setZoomLevel((prevZoom) => {
      let newZoom;
      if (direction === "in") {
        newZoom = Math.min(prevZoom + 5, 100);
      } else {
        newZoom = Math.max(prevZoom - 5, 40);
      }

      console.log("New zoom level:", newZoom);
      localStorage.setItem("songListZoomLevel", newZoom.toString());
      return newZoom;
    });
  };

  const handleProjectAssignment = async (songId, projectIds, assign) => {
    try {
      await updateSubProjectDetailsAPI({
        subproject_id: songId,
        assigned: assign >= 1 ? 2 : 1,
      });
      await attachProjectsToSong(songId, projectIds);
    } catch (error) {
      throw error;
    }
  };

  // Helper function to get unique values with date formatting
  const getUniqueValues = (data, accessor) => {
    console.log("unique");
    if (accessor === "mix_date") {
      const uniqueDates = new Set(
        data
          .map((item) => {
            const date = item.create_at;
            if (!date) return null;
            return new Date(date).toLocaleDateString("en-US", {
              month: "2-digit",
              day: "2-digit",
              year: "2-digit",
            });
          })
          .filter((date) => date !== "Invalid Date" && date !== null)
      );
      const b = Array.from(uniqueDates).sort((a, b) => {
        if (!a) return -1;
        if (!b) return 1;
        return new Date(a) - new Date(b);
      });
      console.log(b, "mix_daten");
      return Array.from(uniqueDates).sort((a, b) => {
        if (!a) return -1;
        if (!b) return 1;
        return new Date(a) - new Date(b);
      });
    }

    // Handle employee-related fields
    if (["is_writer", "is_artist", "is_engineer"].includes(accessor)) {
      const uniqueEmployees = new Set(
        data
          .map((item) => {
            const employee = item.employees?.find(
              (emp) => emp.emp_type === accessor
            );
            return employee?.name || null;
          })
          .filter(Boolean)
      );
      return Array.from(uniqueEmployees).sort();
    }

    // Handle other fields
    const values = new Set(
      data.map((item) => {
        switch (accessor) {
          case "status":
            return item.status;
          case "gender":
            return item.gender;
          case "genre":
            return item.genre;
          case "song_type":
            return item.song_type;
          default:
            return item[accessor];
        }
      })
    );

    return Array.from(values)
      .filter(Boolean)
      .sort((a, b) => {
        if (a === null || a === undefined) return -1;
        if (b === null || b === undefined) return 1;
        return String(a).localeCompare(String(b));
      });
  };

  // Filter application function
  const getFilteredData = (data) => {
    return data.filter((row) => {
      return Object.entries(columnFilters).every(
        ([accessor, excludedValues]) => {
          if (!excludedValues?.length) return true; // No filter applied
          return !excludedValues.includes(row[accessor]);
        }
      );
    });
  };

  // Add handler for edit submission
  const handleEditSong = async (updatedSongData) => {
    try {
      // Add your API call here to update the song
      // const result = await updateSongAPI(updatedSongData);

      showToast(globalDispatch, "Song updated successfully", 5000);
      setShowEditSongModal(false);
      setSelectedSongForEdit(null);
      await callDataAgain(currentPage); // Refresh the table
      await refreshFilters();
    } catch (error) {
      showToast(globalDispatch, error.message, 5000, "error");
    }
  };

  const downloadXLSX = async () => {
    try {
      const sdk = new MkdSDK();
      const result = await sdk.callRawAPI(
        "/v3/api/custom/equality_record/project/download_all_songs",
        {},
        "POST"
      );
      console.log(result, "result");

      // Create workbook
      const workbook = XLSX.utils.book_new();

      // Group songs by id_string to handle duplicates
      const groupedSongs = result.result.reduce((acc, song) => {
        if (!acc[song.id_string]) {
          acc[song.id_string] = [];
        }
        acc[song.id_string].push(song);
        return acc;
      }, {});

      // Transform API data using actual employee data
      const transformedData = Object.values(groupedSongs).map((songs) => {
        const song = songs[0]; // Use first instance for common data

        // Find employees by type
        const writer = song.employees?.find((emp) => emp.is_writer === 1);
        const artist = song.employees?.find((emp) => emp.is_artist === 1);
        const engineer = song.employees?.find((emp) => emp.is_engineer === 1);

        let statusStr = "N/A";
        if (song.workorder_status) {
          statusMapping.forEach((item) => {
            if (Number(item.id) === Number(song.workorder_status)) {
              statusStr = item.name;
            }
          });
        }

        if (
          song.workorder_id &&
          song.workorder_status &&
          song.writer_submit_status &&
          song.workorder_artist_id === song.workorder_engineer_id
        ) {
          statusStr = "Artist/Engineer";
        }

        //

        if (
          song.workorder_id &&
          song.workorder_status &&
          song.workorder_auto_approve === 1 &&
          song.workorder_writer_id === song.workorder_artist_id
        ) {
          if (song.workorder_status === 1) {
            statusStr = "Writer/Artist";
          } else if (song.workorder_status === 5) {
            statusStr = "Completed";
          }
        }

        if (
          song.workorder_id &&
          song.workorder_status &&
          song.workorder_auto_approve === 1 &&
          song.workorder_writer_id === song.workorder_artist_id &&
          song.workorder_writer_id === song.workorder_engineer_id
        ) {
          if (song.workorder_status === 1) {
            statusStr = "Wri/Art/Eng";
          } else if (song.workorder_status === 5) {
            statusStr = "Completed";
          }
        }

        if (song.workorder_status === 5) {
          statusStr = "Completed";
        }

        if (song.type.includes("Upload")) {
          statusStr = "Completed";
        }

        console.log(engineer, artist, writer, "employee");

        // If there are multiple songs with same id_string, combine their project_names
        const assignedTo =
          songs.length > 1
            ? songs
                .filter((s) => s.project_name) // only keep songs with valid project_name
                .map((s) => s.project_name)
                .join(", ")
            : "";

        return [
          song.id_string, // File Name
          engineer?.name || "", // Instrumental Producer
          engineer?.engineer_cost || "", // Inst. Cost
          writer?.name || "", // Writer
          writer?.writer_cost || "", // Write Cost
          artist?.name || "", // Vocalist
          artist?.artist_cost || "", // Vocal Cost
          statusStr, // Progress
          song.gender || "", // Male/Female/Queen
          artist?.name || "", // Artist (same as vocalist)
          song.type_name || "", // Title
          "", // Keywords (empty as specified)
          song.bpm || "", // BPM
          song.song_key || "", // Key
          song.genre || "", // Genre/Type
          assignedTo, // Assigned to (from project_name for duplicates)
          song.song_type || "", // Song Type
        ];
      });

      // Create regular songs sheet data
      const songsSheetData = [
        ["Beats and Songs"],
        [""],
        [
          "File Name",
          "Instrumental Producer",
          "Inst. Cost",
          "Writer",
          "Writer Cost",
          "Vocalist",
          "Vocal Cost",
          "Progress",
          "Male/Female/Queen",
          "Artist",
          "Title",
          "Keywords",
          "BPM",
          "Key",
          "Genre/Type",
          "Assigned to:",
          "Song Type",
        ],
        ...transformedData,
      ];

      // Create team songs sheet data - using actual assigned songs
      const teamSongsData = [
        ["Songs for teams"],
        [""],
        [
          "Assigned to:",
          "File Name",
          "Song Type",
          "Instrumental Producer",
          "Inst. Cost",
          "Writer",
          "Write Cost",
          "Vocalist",
          "Vocal Cost",
          "Progress",
          "Male/Female/Queen",
          "Artist",
          "Title",
          "Keywords",
          "BPM",
          "Key",
          "Genre/Type",
        ],
        // Filter and transform songs that have project_name
        ...Object.values(groupedSongs)
          .filter((songs) => songs.some((s) => s.project_name))
          .map((songs) => {
            const song = songs[0];
            const writer = song.employees?.find((emp) => emp.is_writer === 1);
            const artist = song.employees?.find((emp) => emp.is_artist === 1);
            const engineer = song.employees?.find(
              (emp) => emp.is_engineer === 1
            );

            const assignedTo =
              songs.length > 1
                ? songs
                    .filter((s) => s.project_name) // only keep songs with valid project_name
                    .map((s) => s.project_name)
                    .join(", ")
                : "";

            return [
              assignedTo || "",
              song.id_string || "",
              song.song_type || "",
              engineer?.name || "",
              engineer?.engineer_cost || "",
              writer?.name || "",
              writer?.writer_cost || "",
              artist?.name || "",
              artist?.artist_cost || "",
              song.status === 0 ? "In Progress" : "Complete",
              song.gender || "",
              artist?.name || "",
              song.type_name || "",
              "", // Keywords
              song.bpm || "",
              song.song_key || "",
              song.genre || "",
            ];
          }),
      ];

      // Rest of the function remains the same...
      const sheet1 = XLSX.utils.aoa_to_sheet(songsSheetData);
      const sheet2 = XLSX.utils.aoa_to_sheet(teamSongsData);

      // Apply styles to both sheets
      const applyStyles = (sheet, dataLength) => {
        // Style for title row
        const titleCell = sheet["A1"];
        if (titleCell) {
          titleCell.s = {
            font: { bold: true, sz: 22 },
            alignment: { horizontal: "left" },
          };
        }

        if (!sheet["!rows"]) sheet["!rows"] = [];
        sheet["!rows"][0] = { hpt: 45 }; // Set title row height to 35 points
        // Set row height for header
        if (!sheet["!rows"]) sheet["!rows"] = [];
        sheet["!rows"][2] = { hpt: 30 }; // Set header row height to 30 points

        // Style for all cells including headers
        const columns = [
          "A",
          "B",
          "C",
          "D",
          "E",
          "F",
          "G",
          "H",
          "I",
          "J",
          "K",
          "L",
          "M",
          "N",
          "O",
          "P",
          "Q",
        ];
        for (let row = 3; row <= dataLength + 3; row++) {
          columns.forEach((col) => {
            const cellRef = `${col}${row}`;
            if (!sheet[cellRef]) sheet[cellRef] = { v: "", t: "s" };

            // Base style for all cells
            const baseStyle = {
              alignment: { horizontal: "center", vertical: "center" },
              border: {
                top: { style: "thin" },
                bottom: { style: "thin" },
                left: { style: "thin" },
                right: { style: "thin" },
              },
            };

            // Additional style for header row
            if (row === 3) {
              baseStyle.font = { bold: true };
            }

            sheet[cellRef].s = baseStyle;
          });
        }

        // Column background colors
        const styleRanges = {
          producer: { cols: ["B", "C"], color: "B8CCE4" },
          writer: { cols: ["D", "E"], color: "FFF2CC" },
          vocalist: { cols: ["F", "G"], color: "FFE6E6" },
        };

        Object.values(styleRanges).forEach(({ cols, color }) => {
          cols.forEach((col) => {
            for (let row = 3; row <= dataLength + 3; row++) {
              const cellRef = `${col}${row}`;
              if (!sheet[cellRef]) sheet[cellRef] = { v: "", t: "s" };
              sheet[cellRef].s = {
                ...sheet[cellRef].s,
                fill: { fgColor: { rgb: color }, patternType: "solid" },
              };
            }
          });
        });

        // Set column widths
        const wscols = [
          { wch: 40 }, // File Name - wider
          { wch: 30 }, // Instrumental Producer
          { wch: 20 }, // Inst. Cost
          { wch: 25 }, // Writer
          { wch: 20 }, // Write Cost
          { wch: 25 }, // Vocalist
          { wch: 20 }, // Vocal Cost
          { wch: 35 },
          { wch: 20 },
          { wch: 20 },
          { wch: 25 },
          { wch: 20 },
          { wch: 20 },
          { wch: 25 },
          { wch: 25 },
          { wch: 25 },
          { wch: 25 },
          // ... rest of the columns ...
        ];

        sheet["!cols"] = wscols;
        sheet["!merges"] = [{ s: { r: 0, c: 0 }, e: { r: 0, c: 16 } }];
      };

      applyStyles(sheet1, transformedData.length);
      applyStyles(
        sheet2,
        Object.values(groupedSongs).filter((songs) =>
          songs.some((s) => s.project_name)
        ).length
      );

      // Add sheets to workbook
      XLSX.utils.book_append_sheet(workbook, sheet1, "Songs 2024-2025");
      XLSX.utils.book_append_sheet(workbook, sheet2, "Team Songs");

      // Write file and trigger download
      XLSX.writeFile(workbook, "2024-2025_Songs.xlsx");

      showToast(globalDispatch, "File downloaded successfully", 3000);
    } catch (error) {
      console.error("Download error:", error);
      showToast(globalDispatch, "Failed to download file", 3000, "error");
    }
  };

  React.useEffect(() => {
    (async function () {
      try {
        const result = await getAllEmployeeByGroup();
        console.log(result);
      } catch (error) {
        console.log(error);
      }
    })();
  }, []);

  const handleMoveClick = () => {
    setIsMoveModeActive(true);
  };

  const handleMoveSongs = async () => {
    if (!selectedMixSeason || selectedSongsForMove.length === 0) {
      showToast(
        globalDispatch,
        "Please select songs and a mix season",
        3000,
        "error"
      );
      return;
    }

    try {
      const sdk = new MkdSDK();

      // Create an array of promises for each song move operation
      const movePromises = selectedSongsForMove.map(async (songId) => {
        return sdk.callRawAPI(
          "/v3/api/custom/equality_record/project/move_song_to_new_mix_season",
          {
            mix_season:
              mixSeasons.find((elem) => elem.id == selectedMixSeason)?.id || "",
            subproject_id: songId, // Send single song ID in array
          },
          "POST"
        );
      });

      // Wait for all move operations to complete
      const results = await Promise.all(movePromises);

      // Check if any operation failed
      const hasError = results.some((result) => result.error);

      if (!hasError) {
        showToast(globalDispatch, "Songs moved successfully", 3000);
        setSelectedSongsForMove([]);
        setIsMoveModeActive(false);
        setShowMoveModal(false);
        await callDataAgain(currentPage);
      } else {
        showToast(globalDispatch, "Some songs failed to move", 3000, "error");
      }
    } catch (error) {
      showToast(globalDispatch, error.message, 3000, "error");
    }
  };

  console.log(downloadFilters, "filters");

  // Update the handleBulkDownload function
  const handleBulkDownload = async () => {
    try {
      const sdk = new MkdSDK();
      const payload = {
        ...(downloadFilters.id_range.start &&
          downloadFilters.id_range.end && {
            id_string: downloadFilters?.id_range?.array,
          }),
        ...(downloadFilters.mix_date_range.start &&
          downloadFilters.mix_date_range.end && {
            mix_date_range: {
              start: moment(downloadFilters.mix_date_range.start).format(
                "YYYY-MM-DD HH:mm:ss"
              ),
              end: moment(downloadFilters.mix_date_range.end).format(
                "YYYY-MM-DD HH:mm:ss"
              ),
            },
          }),
        ...(downloadFilters.writer_id && {
          writer_id: downloadFilters.writer_id,
        }),
        ...(downloadFilters.artist_id && {
          artist_id: downloadFilters.artist_id,
        }),
        ...(downloadFilters.engineer_id && {
          engineer_id: downloadFilters.engineer_id,
        }),
      };

      // Initialize download manager if it doesn't exist
      window.downloadManager = window.downloadManager || {
        downloads: new Map(),
        progressBox: null,
      };

      // Create progress box if it doesn't exist
      if (!window.downloadManager.progressBox) {
        window.downloadManager.progressBox = createDownloadProgressBox();
      }

      const downloadId = Date.now();
      window.downloadManager.downloads.set(downloadId, {
        fileName: `songs_${moment().format("YYYY-MM-DD_HH-mm")}.zip`,
        progress: 0,
        status: "starting",
        type: "master",
      });

      window.downloadManager.progressBox.updateDownloads(
        window.downloadManager.downloads
      );

      const result = await sdk.callRawAPI(
        "/v3/api/custom/equality_record/project/download_all_songs",
        { filter: payload },
        "POST"
      );

      if (!result.error && result.result?.length > 0) {
        const zip = new JSZip();
        const totalSongs = result.result.length;
        let processedFiles = 0;
        let totalFiles = 0;
        let completedFiles = 0;

        // First, count total files to download
        result.result.forEach((song) => {
          if (song.lyrics) totalFiles++;
          if (song.masters?.length) totalFiles += song.masters.length;
          if (song.admin_writer_instrumentals?.length)
            totalFiles += song.admin_writer_instrumentals.length;
        });

        // Update status to show total files
        window.downloadManager.downloads.set(downloadId, {
          fileName: `songs_${moment().format("YYYY-MM-DD_HH-mm")}.zip`,
          progress: 0,
          status: `Processing 0/${totalFiles} files`,
          type: "bulk",
        });
        window.downloadManager.progressBox.updateDownloads(
          window.downloadManager.downloads
        );

        for (const song of result.result) {
          try {
            const artist = song.employees?.find(
              (emp) => emp.emp_type === "artist"
            );
            const folderParts = [
              song.id_string,
              artist?.name || "noartistyet",
              song.type_name,
              song.song_key,
              song.bpm,
            ].filter(Boolean);

            const folderName =
              folderParts.length > 1
                ? `${folderParts[0]}_${folderParts[1]}${folderParts
                    .slice(2)
                    .map((part) => `-${part}`)
                    .join("")}`
                : folderParts[0];

            const songFolder = zip.folder(folderName);

            // Add lyrics PDF
            if (song.lyrics) {
              try {
                const lyricsPdfBlob = await generatePdfBlobCombined(
                  song.lyrics
                );
                await songFolder.file("lyrics.pdf", lyricsPdfBlob);
                completedFiles++;
                updateProgress(completedFiles, totalFiles);
              } catch (error) {
                console.error(
                  `Error creating lyrics PDF for ${song.id_string}:`,
                  error
                );
              }
            }

            // Add master files
            if (song.masters?.length > 0) {
              for (const masterFile of song.masters) {
                if (masterFile.url) {
                  try {
                    const masterResponse = await fetch(masterFile.url);
                    if (!masterResponse.ok)
                      throw new Error(
                        `HTTP error! status: ${masterResponse.status}`
                      );
                    const masterBlob = await masterResponse.blob();
                    const masterFileName = masterFile.url.split("/").pop();
                    await songFolder.file(
                      `masters/${masterFileName}`,
                      masterBlob
                    );
                    completedFiles++;
                    updateProgress(completedFiles, totalFiles);
                  } catch (error) {
                    console.error(
                      `Error downloading master file: ${masterFile.url}`,
                      error
                    );
                  }
                }
              }
            }

            // Add admin files
            if (song.admin_writer_instrumentals?.length > 0) {
              for (const adminFile of song.admin_writer_instrumentals) {
                if (adminFile.url) {
                  try {
                    const adminResponse = await fetch(adminFile.url);
                    if (!adminResponse.ok)
                      throw new Error(
                        `HTTP error! status: ${adminResponse.status}`
                      );
                    const adminBlob = await adminResponse.blob();
                    const adminFileName = adminFile.url.split("/").pop();
                    await songFolder.file(`admin/${adminFileName}`, adminBlob);
                    completedFiles++;
                    updateProgress(completedFiles, totalFiles);
                  } catch (error) {
                    console.error(
                      `Error downloading admin file: ${adminFile.url}`,
                      error
                    );
                  }
                }
              }
            }

            processedFiles++;
          } catch (error) {
            console.error(`Error processing song ${song.id_string}:`, error);
          }
        }

        // Update status to generating zip
        window.downloadManager.downloads.set(downloadId, {
          fileName: `songs_${moment().format("YYYY-MM-DD_HH-mm")}.zip`,
          progress: 95,
          status: "Generating zip file...",
          type: "bulk",
        });
        window.downloadManager.progressBox.updateDownloads(
          window.downloadManager.downloads
        );

        const content = await zip.generateAsync({
          type: "blob",
          compression: "DEFLATE",
          compressionOptions: { level: 5 },
        });

        const link = document.createElement("a");
        link.href = URL.createObjectURL(content);
        link.download = `songs_${moment().format("YYYY-MM-DD_HH-mm")}.zip`;
        document.body.appendChild(link);
        link.click();

        // Update status to complete
        window.downloadManager.downloads.set(downloadId, {
          fileName: `songs_${moment().format("YYYY-MM-DD_HH-mm")}.zip`,
          progress: 100,
          status: "complete",
          type: "bulk",
        });
        window.downloadManager.progressBox.updateDownloads(
          window.downloadManager.downloads
        );

        // Cleanup
        setTimeout(() => {
          URL.revokeObjectURL(link.href);
          document.body.removeChild(link);
          window.downloadManager.downloads.delete(downloadId);
          if (window.downloadManager.downloads.size === 0) {
            window.downloadManager.progressBox.remove();
            window.downloadManager.progressBox = null;
          } else {
            window.downloadManager.progressBox.updateDownloads(
              window.downloadManager.downloads
            );
          }
        }, 2000);

        setShowDownloadModal(false);
      } else {
        throw new Error(result.message || "No songs found to download");
      }
    } catch (error) {
      console.error("Download error:", error);

      const downloadId = Date.now();
      // Update status to failed
      if (window.downloadManager?.downloads) {
        window.downloadManager.downloads.set(downloadId, {
          fileName: `songs_${moment().format("YYYY-MM-DD_HH-mm")}.zip`,
          progress: 0,
          status: "failed",
          type: "bulk",
        });
        window.downloadManager.progressBox.updateDownloads(
          window.downloadManager.downloads
        );
      }
      showToast(
        globalDispatch,
        `Download failed: ${error.message}`,
        5000,
        "error"
      );
    }
  };
  const downloadId = Date.now();
  // Helper function to update progress
  const updateProgress = (completed, total) => {
    const progress = Math.round((completed / total) * 100);
    window.downloadManager.downloads.set(downloadId, {
      fileName: `songs_${moment().format("YYYY-MM-DD_HH-mm")}.zip`,
      progress,
      status: `Processing ${completed}/${total} files`,
      type: "bulk",
    });
    window.downloadManager.progressBox.updateDownloads(
      window.downloadManager.downloads
    );
  };

  const handleResetEmployee = async (data) => {
    try {
      const result = await resetSubProjectEmployeeAPI(data);
      if (!result.error) {
        showToast(globalDispatch, result.message, 2000);
        await callDataAgain(currentPage); // Refresh the table data
      } else {
        showToast(globalDispatch, result.message, 2000, "error");
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  const handleEmployeeChange = async (data) => {
    try {
      const result = await updateSubProjectEmployeeAPI(data);
      if (!result.error) {
        showToast(globalDispatch, result.message, 2000);
        await callDataAgain(currentPage);
      } else {
        showToast(globalDispatch, result.message, 2000, "error");
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  // Update handleFilterChange to handle employee filters
  const handleFilterChange = (accessor, excludedValues) => {
    if (["is_writer", "is_artist", "is_engineer"].includes(accessor)) {
      // Get all selected employee names
      const selectedNames = columnValues[accessor]?.filter(
        (name) => !excludedValues.includes(name)
      );

      if (selectedNames?.length > 0) {
        // Create employee filter condition
        const empType = accessor.replace("is_", "");
        const filterString = `name IN (${selectedNames
          .map((name) => `'${name}'`)
          .join(",")})`;

        setActiveFilters((prev) => {
          // Remove any existing employee filters for this type

          // Add new employee filter
          return [...prev, `employee_filter:["${filterString}"]`];
        });
      } else {
        // Remove employee filter for this type
        setActiveFilters((prev) =>
          prev.filter(
            (f) => !f.includes(`emp_type = '${accessor.replace("is_", "")}'`)
          )
        );
      }
      return;
    }

    if (isRangeColumn(accessor)) {
      const { min, max } = rangeFilters[accessor];

      // Special handling for BPM ranges
      if (accessor === "bpm") {
        let filterString;
        if (min <= 75) {
          filterString = `bpm <= 75`;
        } else if (min >= 76 && max <= 120) {
          filterString = `bpm BETWEEN 76 AND 120`;
        } else if (min >= 121 && max <= 140) {
          filterString = `bpm BETWEEN 121 AND 140`;
        } else if (min >= 141 && max <= 150) {
          filterString = `bpm BETWEEN 141 AND 150`;
        } else if (min >= 151) {
          filterString = `bpm >= 151`;
        }

        if (filterString) {
          setActiveFilters((prev) => {
            const filtered = prev.filter((f) => !f.includes("bpm"));
            return [...filtered, filterString];
          });
        } else {
          setActiveFilters((prev) => prev.filter((f) => !f.includes("bpm")));
        }
        return;
      }

      // Original range filter logic for other columns
      if (min !== 0 || max !== 100) {
        const filterString = `${accessor} BETWEEN ${min} AND ${max}`;
        setActiveFilters((prev) => {
          const filtered = prev.filter((f) => !f.startsWith("employee_filter"));
          return [...filtered, `employee_filter:["${filterString}"]`];
        });
      } else {
        setActiveFilters((prev) =>
          prev.filter((f) => !f.startsWith("employee_filter"))
        );
      }
      return;
    }

    if (isDateColumn(accessor)) {
      // Handle date filter
      const selectedDates = columnValues[accessor]?.filter(
        (date) => !excludedValues.includes(date)
      );

      if (selectedDates?.length > 0) {
        const formattedDates = selectedDates
          .map((date) => `'${new Date(date).toISOString()}'`)
          .join(",");

        const filterString = `sp.mix_date IN (${formattedDates})`;

        setActiveFilters((prev) => {
          const filtered = prev.filter((f) => !f.startsWith("sp.mix_date"));
          return [...filtered, filterString];
        });
      } else {
        setActiveFilters((prev) =>
          prev.filter((f) => !f.startsWith("sp.mix_date"))
        );
      }
      return;
    }

    // Original logic for other columns
    const allValues = columnValues[accessor] || [];
    const selectedValues = allValues.filter(
      (value) => !excludedValues.includes(value)
    );

    if (selectedValues.length > 0 && selectedValues.length < allValues.length) {
      const isNumeric = typeof selectedValues[0] === "number";
      const values = isNumeric
        ? selectedValues.join(",")
        : selectedValues.map((v) => `'${v}'`).join(",");

      const filterString = `${accessor} IN (${values})`;

      setActiveFilters((prev) => {
        const filtered = prev.filter((f) => !f.startsWith(`${accessor} IN`));
        return [...filtered, filterString];
      });
    } else {
      setActiveFilters((prev) =>
        prev.filter((f) => !f.startsWith(`${accessor} IN`))
      );
    }
  };

  // Update fetchAllColumnValues to handle employee names
  const fetchAllColumnValues = async () => {
    try {
      const filterableColumns = columns
        .filter(
          (col) =>
            col.accessor !== "select" &&
            col.accessor !== "actions" &&
            col.accessor !== "status" &&
            col.accessor !== "assigned_to" &&
            col.accessor !== "edit" &&
            !isDateColumn(col.accessor)
        )
        .map((col) => {
          // Map employee-type accessors to 'name'
          if (
            ["is_engineer", "is_writer", "is_artist"].includes(col.accessor)
          ) {
            return "name";
          }

          return col.accessor;
        });

      const promises = filterableColumns.map(async (accessor) => {
        const sdk = new MkdSDK();
        let endpoint = `/v3/api/custom/equality_record/project/sub_project/column?type=${accessor}`;

        // Special handling for employee names
        if (accessor === "name") {
          endpoint =
            "/v3/api/custom/equality_record/project/sub_project/column?type=name";
        }

        const result = await sdk.callRawAPI(endpoint, {}, "GET");

        if (!result.error && result.list) {
          let values;
          if (accessor === "name") {
            // Process employee names for each type
            values = {
              is_writer: [
                ...new Set(
                  result.list
                    .map((item) => item["name"])
                    .filter(
                      (value) =>
                        value !== null && value !== undefined && value !== ""
                    )
                ),
              ],
              is_artist: [
                ...new Set(
                  result.list
                    .map((item) => item["name"])
                    .filter(
                      (value) =>
                        value !== null && value !== undefined && value !== ""
                    )
                ),
              ],
              is_engineer: [
                ...new Set(
                  result.list
                    .map((item) => item["name"])
                    .filter(
                      (value) =>
                        value !== null && value !== undefined && value !== ""
                    )
                ),
              ],
            };
          } else {
            values = result.list
              .map((item) => item[accessor])
              .filter(
                (value) => value !== null && value !== undefined && value !== ""
              );
          }

          // Return object with values for each accessor
          if (accessor === "name") {
            return values;
          }
          return { [accessor]: [...new Set(values)].sort() };
        }
        return accessor === "name" ? {} : { [accessor]: [] };
      });

      const results = await Promise.all(promises);

      // Combine all results
      const newColumnValues = results.reduce((acc, curr) => {
        if (curr.is_writer || curr.is_artist || curr.is_engineer) {
          // Spread employee type values
          return { ...acc, ...curr };
        }
        return { ...acc, ...curr };
      }, {});

      setColumnValues(newColumnValues);
      setBaseFilters(newColumnValues);
    } catch (error) {
      console.error("Error fetching column values:", error);
      showToast(globalDispatch, "Failed to load filters", 3000, "error");
    }
  };

  console.log(baseFilters, "filters", activeFilters);

  // Update the Apply button click handler in filter menu
  const handleApplyFilter = (accessor) => {
    setShowFilterMenu(null); // Close menu first

    if (accessor === "program_name") {
      // Special handling for program_name filter
      const selectedPrograms = getFilterOptions(accessor).filter(
        (value) => !columnFilters[accessor]?.includes(value)
      );

      if (selectedPrograms.length > 0) {
        setActiveFilters((prev) => {
          // Remove any existing program filters
          const filtered = prev.filter((f) => !f.includes("c.program"));
          // Add new program filters in the desired format
          const programFilters = selectedPrograms.map(
            (program) => `c.program = '${program}'`
          );
          return [...filtered, ...programFilters];
        });
      } else {
        // If no programs selected, remove program filters
        setActiveFilters((prev) =>
          prev.filter((f) => !f.includes("c.program"))
        );
      }
      return;
    }

    if (isDateColumn(accessor)) {
      const { startDate, endDate } = mixDateFilterRange;

      setActiveFilters((prev) => {
        // Remove any existing filter for this date column
        const filtered = prev.filter(
          (f) => !f.startsWith(`sp.${accessor} BETWEEN`)
        );

        if (startDate && endDate) {
          // Format dates: Start of the start day, End of the end day
          // Use the requested format 'YYYY-MM-DD HH:mm:ss'
          const startFormatted = moment(startDate)
            .startOf("day")
            .format("YYYY-MM-DDTHH:mm:ss.SSS[Z]");
          const endFormatted = moment(endDate)
            .endOf("day")
            .format("YYYY-MM-DDTHH:mm:ss.SSS[Z]");
          const filterString = `sp.${accessor} BETWEEN '${startFormatted}' AND '${endFormatted}'`;
          return [...filtered, filterString];
        } else {
          // If dates are cleared or incomplete, just return the filtered list (removing the filter)
          return filtered;
        }
      });
    } else if (isRangeColumn(accessor)) {
      // Handle existing range columns (cost, bpm)
      // Use the rangeFilters state for these
      const { min, max } = rangeFilters[accessor];
      let filterString = "";

      if (accessor === "bpm") {
        // ... (keep existing BPM range logic) ...
        if (min <= 75 && max <= 75) {
          // Adjusted condition slightly
          filterString = `bpm <= 75`;
        } else if (min >= 76 && max <= 120) {
          filterString = `bpm BETWEEN 76 AND 120`;
        } else if (min >= 121 && max <= 140) {
          filterString = `bpm BETWEEN 121 AND 140`;
        } else if (min >= 141 && max <= 150) {
          filterString = `bpm BETWEEN 141 AND 150`;
        } else if (min >= 151) {
          // Adjusted condition slightly
          filterString = `bpm >= 151`;
        }
        setActiveFilters((prev) => {
          const filtered = prev.filter((f) => !f.includes("bpm")); // Remove any bpm filter
          return filterString ? [...filtered, filterString] : filtered; // Add new one if exists
        });
      } else {
        // Cost columns
        // Assuming default range means no filter, otherwise apply BETWEEN
        const defaultValue =
          accessor === "artist_cost" ||
          accessor === "writer_cost" ||
          accessor === "engineer_cost"
            ? { min: 0, max: 100 }
            : { min: 0, max: 200 }; // Define default ranges if needed
        if (min !== defaultValue.min || max !== defaultValue.max) {
          // Check against default/max values if needed
          filterString = `${accessor} BETWEEN ${min} AND ${max}`;
          // Assuming cost filters go into employee_filter as before
          setActiveFilters((prev) => {
            const filtered = prev.filter(
              (f) =>
                !f.startsWith("employee_filter:") ||
                !f.includes(`${accessor} BETWEEN`)
            ); // Remove previous range for this accessor
            return [...filtered, `employee_filter:["${filterString}"]`];
          });
        } else {
          // Remove the filter if it's back to the default range
          setActiveFilters((prev) =>
            prev.filter(
              (f) =>
                !f.startsWith("employee_filter:") ||
                !f.includes(`${accessor} BETWEEN`)
            )
          );
        }
      }
    } else {
      // Handle regular multi-select filters
      const excludedValues = columnFilters[accessor] || [];
      handleFilterChange(accessor, excludedValues); // Use the existing function for these
    }
  };

  // Update the Clear button click handler in filter menu
  const handleClearFilter = (accessor) => {
    if (isDateColumn(accessor)) {
      // Reset date range
      setMixDateFilterRange({ startDate: null, endDate: null });
      setMixDateFilterFocusedInput(null);
    } else if (isRangeColumn(accessor)) {
      // Reset range filters to default values
      setRangeFilters((prev) => ({
        ...prev,
        [accessor]:
          accessor === "bpm" ? { min: 0, max: 200 } : { min: 0, max: 100 },
      }));
    }

    // Reset column filters
    setColumnFilters((prev) => {
      const newFilters = { ...prev };
      delete newFilters[accessor];
      return newFilters;
    });

    // Reset filter search values
    setFilterSearchValues((prev) => {
      const newValues = { ...prev };
      delete newValues[accessor];
      return newValues;
    });

    // Reset active filters
    setActiveFilters((prev) => {
      if (["is_writer", "is_artist", "is_engineer"].includes(accessor)) {
        return prev.filter((f) => !f.includes('employee_filter:["name IN'));
      }
      if (isDateColumn(accessor)) {
        return prev.filter((f) => !f.startsWith(`sp.${accessor}`));
      }
      return prev.filter((f) => !f.startsWith(`${accessor}`));
    });

    setShowFilterMenu(null);
  };

  // Helper function to check if a filter is active
  const isFilterActive = (accessor) => {
    if (isDateColumn(accessor)) {
      return (
        mixDateFilterRange.startDate !== null ||
        mixDateFilterRange.endDate !== null
      );
    }
    if (isRangeColumn(accessor)) {
      const { min, max } = rangeFilters[accessor];
      const defaultMin = 0;
      const defaultMax = accessor === "bpm" ? 200 : 100;
      return min !== defaultMin || max !== defaultMax;
    }
    if (["is_writer", "is_artist", "is_engineer"].includes(accessor)) {
      return activeFilters.some((f) => f.includes(`employee_filter:["name IN`));
    }
    return activeFilters.some((f) => f.startsWith(`${accessor}`));
  };

  // Update the validation function to allow any number after the year
  const isValidIdFormat = (id) => {
    // Matches format like "2324-1" or "2324-112" or "2324-400" (year-number)
    return /^\d{4}-\d+$/.test(id);
  };

  // Update the generate range function to handle non-padded numbers
  const generateIdRange = (start, end) => {
    if (!start || !end || !isValidIdFormat(start) || !isValidIdFormat(end)) {
      return [];
    }

    const [startYear, startNumStr] = start.split("-");
    const [endYear, endNumStr] = end.split("-");
    const startNum = parseInt(startNumStr);
    const endNum = parseInt(endNumStr);

    const numLength = Math.max(startNumStr.length, endNumStr.length);
    // Validate years match
    if (startYear !== endYear) {
      return [];
    }

    // Validate start is less than end
    if (startNum > endNum) {
      return [];
    }

    // Generate array of IDs (without padding the numbers)
    const ids = [];
    for (let i = startNum; i <= endNum; i++) {
      // Pad the number to match the original format length
      const paddedNum = i.toString().padStart(numLength, "0");
      ids.push(`${startYear}-${paddedNum}`);
    }
    return ids;
  };

  // Add this function to refresh filters after changes
  const refreshFilters = async () => {
    await fetchAllColumnValues();
  };

  const handleFilterMenuClick = (accessor) => {
    if (showFilterMenu === accessor) {
      // Destroy the popper instance when closing
      if (popperInstances[accessor]) {
        popperInstances[accessor].destroy();
        const newInstances = { ...popperInstances };
        delete newInstances[accessor];
        setPopperInstances(newInstances);
      }
      setShowFilterMenu(null);
    } else {
      setShowFilterMenu(accessor);
      // Create new popper instance after a small delay to ensure elements are mounted
      setTimeout(() => {
        const buttonElement = filterButtonRefs[accessor];
        const menuElement = document.querySelector(
          `[data-filter-menu="${accessor}"]`
        );

        if (buttonElement && menuElement) {
          const instance = createPopper(buttonElement, menuElement, {
            placement: "bottom-start",
            strategy: "fixed",
            modifiers: [
              {
                name: "offset",
                options: {
                  offset: [0, 10],
                },
              },
              {
                name: "preventOverflow",
                options: {
                  boundary: "viewport",
                  padding: 10,
                  altAxis: true,
                },
              },
              {
                name: "flip",
                options: {
                  fallbackPlacements: ["bottom-start", "top-end", "bottom-end"],
                },
              },
            ],
          });
          setPopperInstances((prev) => ({ ...prev, [accessor]: instance }));
        }
      }, 0);
    }
  };

  // Update the lyrics search to use filters state
  const handleLyricsSearch = (value) => {
    setLyricsSearch(value);
    setFilters((prev) => ({
      ...prev,
      lyrics: value,
    }));
  };

  // Modify the filter menu UI to show range slider for cost columns
  const renderFilterContent = (accessor) => {
    // Modify the date range filter section in renderFilterContent
    if (isDateColumn(accessor)) {
      return (
        <div className="p-6" onClick={(e) => e.stopPropagation()}>
          {" "}
          <div className="mb-4">
            <label className="mb-2 block text-[12px] font-medium">
              Select Date Range
            </label>
            <div
              className="relative w-[320px]" // Add relative positioning
              onClick={(e) => {
                e.preventDefault(); // Prevent any default actions
                e.stopPropagation(); // Stop propagation
              }}
            >
              <DateRangePicker
                startDate={
                  mixDateFilterRange.startDate
                    ? moment(mixDateFilterRange.startDate)
                    : null
                }
                startDateId={`filter_start_date_${accessor}`}
                endDate={
                  mixDateFilterRange.endDate
                    ? moment(mixDateFilterRange.endDate)
                    : null
                }
                endDateId={`filter_end_date_${accessor}`}
                onDatesChange={({ startDate, endDate }) => {
                  // Prevent the filter menu from closing when selecting dates
                  setTimeout(() => {
                    setMixDateFilterRange({ startDate, endDate });
                  }, 0);
                }}
                focusedInput={mixDateFilterFocusedInput}
                onFocusChange={(focusedInput) => {
                  // Prevent the filter menu from closing when focusing inputs
                  setTimeout(() => {
                    setMixDateFilterFocusedInput(focusedInput);
                  }, 0);
                }}
                numberOfMonths={1}
                isOutsideRange={() => false}
                displayFormat="MM-DD-YYYY"
                showClearDates={true}
                small={true}
                noBorder={true}
                block
                // Remove appendToBody prop as it might cause positioning issues
                readOnly={true}
                customInputIcon={null}
                // Add these props to prevent unwanted closing
                keepOpenOnDateSelect={true}
                reopenPickerOnClearDates={true}
              />
            </div>
          </div>
          <div className="flex justify-between gap-2">
            <button
              className="w-full rounded bg-primary p-1 text-xs hover:bg-opacity-90"
              onClick={(e) => {
                e.preventDefault();
                e.stopPropagation();
                handleClearFilter(accessor);
              }}
            >
              Clear
            </button>
            <button
              className="w-full rounded bg-meta-7 p-1 text-xs hover:bg-opacity-90"
              onClick={(e) => {
                e.preventDefault();
                e.stopPropagation();
                handleApplyFilter(accessor);
              }}
            >
              Apply
            </button>
          </div>
        </div>
      );
    }

    if (isRangeColumn(accessor)) {
      if (accessor === "bpm") {
        const bpmRanges = [
          { label: "75 BPM and below", min: 0, max: 75 },
          { label: "76-120 BPM", min: 76, max: 120 },
          { label: "121-140 BPM", min: 121, max: 140 },
          { label: "141-150 BPM", min: 141, max: 150 },
          { label: "151 BPM and above", min: 151, max: 999 },
        ];

        return (
          <div className="p-4">
            <div className="mb-4">
              <label className="mb-2 block text-sm font-medium">
                BPM Ranges
              </label>
              {bpmRanges.map((range, index) => (
                <div key={index} className="mb-2">
                  <label className="flex items-center gap-2 text-xs">
                    <input
                      type="radio"
                      name="bpmRange"
                      checked={
                        rangeFilters.bpm.min === range.min &&
                        rangeFilters.bpm.max === range.max
                      }
                      onChange={() =>
                        setRangeFilters((prev) => ({
                          ...prev,
                          bpm: { min: range.min, max: range.max },
                        }))
                      }
                      className="form-radio rounded border-strokedark"
                    />
                    {range.label}
                  </label>
                </div>
              ))}
            </div>
            <div className="flex justify-between gap-2">
              <button
                className="w-full rounded bg-primary p-1 text-xs hover:bg-opacity-90"
                onClick={() => handleClearFilter(accessor)}
              >
                Clear
              </button>
              <button
                className="w-full rounded bg-meta-7 p-1 text-xs hover:bg-opacity-90"
                onClick={() => handleApplyFilter(accessor)}
              >
                Apply
              </button>
            </div>
          </div>
        );
      }

      // Original range filter UI for other columns
      const maxValue = Math.max(...(columnValues[accessor] || [0]));
      return (
        <div className="p-4">
          <div className="mb-4">
            <label className="mb-2 block text-sm font-medium">Range</label>
            <div className="flex items-center gap-2">
              <input
                type="number"
                min="0"
                max={maxValue}
                value={rangeFilters[accessor].min}
                onChange={(e) =>
                  setRangeFilters((prev) => ({
                    ...prev,
                    [accessor]: {
                      ...prev[accessor],
                      min: parseInt(e.target.value),
                    },
                  }))
                }
                className="w-20 rounded border border-strokedark bg-form-input p-1"
              />
              <span>to</span>
              <input
                type="number"
                min="0"
                max={maxValue}
                value={rangeFilters[accessor].max}
                onChange={(e) =>
                  setRangeFilters((prev) => ({
                    ...prev,
                    [accessor]: {
                      ...prev[accessor],
                      max: parseInt(e.target.value),
                    },
                  }))
                }
                className="w-20 rounded border border-strokedark bg-form-input p-1"
              />
            </div>
          </div>
          <div className="flex justify-between gap-2">
            <button
              className="w-full rounded bg-primary p-1 text-xs hover:bg-opacity-90"
              onClick={() => handleClearFilter(accessor)}
            >
              Clear
            </button>
            <button
              className="w-full rounded bg-meta-7 p-1 text-xs hover:bg-opacity-90"
              onClick={() => handleApplyFilter(accessor)}
            >
              Apply
            </button>
          </div>
        </div>
      );
    }

    // Updated non-range filter UI
    return (
      <div>
        {/* Search within filter */}
        <div className="border-b border-strokedark p-2">
          <input
            type="text"
            placeholder="Search..."
            className="w-full rounded border border-strokedark bg-form-input p-1 text-xs text-white"
            value={filterSearchValues[accessor] || ""}
            onChange={(e) => {
              setFilterSearchValues({
                ...filterSearchValues,
                [accessor]: e.target.value,
              });
            }}
          />
        </div>

        {/* Select All Option */}
        <div className="border-b border-strokedark p-2">
          <label className="flex items-center gap-2 text-xs">
            <input
              type="checkbox"
              checked={
                !columnFilters[accessor] || columnFilters[accessor].length === 0
              }
              onChange={(e) => {
                if (e.target.checked) {
                  setColumnFilters({
                    ...columnFilters,
                    [accessor]: [],
                  });
                } else {
                  setColumnFilters({
                    ...columnFilters,
                    [accessor]: getFilterOptions(accessor),
                  });
                }
              }}
              className="form-checkbox rounded border-strokedark"
            />
            (Select All)
          </label>
        </div>

        {/* Scrollable Options List */}
        <div className="max-h-[250px] overflow-y-auto">
          {getFilterOptions(accessor)
            .filter((value) =>
              String(value)
                .toLowerCase()
                .includes((filterSearchValues[accessor] || "").toLowerCase())
            )
            .map((value, idx) => (
              <div key={idx} className="p-2 hover:bg-boxdark-2">
                <label className="flex items-center gap-2 text-xs">
                  <input
                    type="checkbox"
                    checked={!columnFilters[accessor]?.includes(value)}
                    onChange={(e) => {
                      const currentFilters = columnFilters[accessor] || [];
                      if (e.target.checked) {
                        setColumnFilters({
                          ...columnFilters,
                          [accessor]: currentFilters.filter((v) => v !== value),
                        });
                      } else {
                        setColumnFilters({
                          ...columnFilters,
                          [accessor]: [...currentFilters, value],
                        });
                      }
                    }}
                    className="form-checkbox rounded border-strokedark"
                  />
                  <span>
                    {" "}
                    {(value?.toString()?.length > 30
                      ? value.toString().substring(0, 30) + "..."
                      : value) || "(empty)"}
                  </span>
                </label>
              </div>
            ))}
        </div>

        {/* Action Buttons */}
        <div className="flex justify-between gap-2 border-t border-strokedark p-2">
          <button
            className="w-full rounded bg-primary p-1 text-xs hover:bg-opacity-90"
            onClick={() => handleClearFilter(accessor)}
          >
            Clear
          </button>
          <button
            className="w-full rounded bg-meta-7 p-1 text-xs hover:bg-opacity-90"
            onClick={() => handleApplyFilter(accessor)}
          >
            Apply
          </button>
        </div>
      </div>
    );
  };

  // Add useRef hook at the top with other hooks
  const filterMenuRef = useRef(null);

  // Add useEffect to handle outside clicks
  useEffect(() => {
    const handleClickOutside = (event) => {
      if (
        filterMenuRef.current &&
        !filterMenuRef.current.contains(event.target)
      ) {
        setShowFilterMenu(null);
      }
    };

    document.addEventListener("mousedown", handleClickOutside);
    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, []);

  const [focusedInput, setFocusedInput] = React.useState({
    mixDateStart: null,
    mixDateEnd: null,
  });
  const [dates, setDates] = React.useState({
    mixDateStart: null,
    mixDateEnd: null,
  });

  return (
    <div className="max-w-screen h-full p-4 md:p-6 lg:p-8">
      <div className="shadow-default rounded border border-strokedark bg-boxdark">
        <div className="flex items-center justify-between border-b border-strokedark px-4 md:px-6 2xl:px-9">
          <h4 className="my-3 text-2xl font-semibold text-white dark:text-white">
            Songs
          </h4>
          <div className="flex items-center gap-2">
            <div className="flex items-center gap-1 rounded bg-boxdark-2 p-1">
              <button
                type="button"
                className={`inline-flex h-8 w-8 items-center justify-center rounded ${
                  zoomLevel > 40
                    ? "hover:bg-primary/80"
                    : "cursor-not-allowed opacity-50"
                }`}
                onClick={() => handleZoom("out")}
                disabled={zoomLevel <= 40}
                title="Zoom Out (5%)"
              >
                <FontAwesomeIcon icon="fa-solid fa-minus" className="h-3 w-3" />
              </button>

              <span className="min-w-[60px] text-center text-sm font-medium">
                {zoomLevel}%
              </span>

              <button
                type="button"
                className={`inline-flex h-8 w-8 items-center justify-center rounded ${
                  zoomLevel < 100
                    ? "hover:bg-primary/80"
                    : "cursor-not-allowed opacity-50"
                }`}
                onClick={() => handleZoom("in")}
                disabled={zoomLevel >= 100}
                title="Zoom In (5%)"
              >
                <FontAwesomeIcon icon="fa-solid fa-plus" className="h-3 w-3" />
              </button>
            </div>

            <div className="flex items-center gap-2">
              <button
                type="button"
                className="inline-flex h-9 items-center justify-center rounded bg-success px-4 py-2 text-sm font-medium text-white hover:bg-opacity-90"
                onClick={downloadXLSX}
                title="Download as Excel spreadsheet"
              >
                <FontAwesomeIcon
                  icon="fa-solid fa-file-excel"
                  className="h-4 w-4"
                />
              </button>

              <button
                type="button"
                className="inline-flex h-9 items-center justify-center rounded bg-primary px-4 py-2 text-sm font-medium text-white hover:bg-opacity-90"
                onClick={() => setShowDownloadModal(true)}
                title="Download song files in bulk"
              >
                <FontAwesomeIcon
                  icon="fa-solid fa-file-zipper"
                  className="h-4 w-4"
                />
              </button>

              {/* Download Modal */}
              {showDownloadModal && (
                <div className="fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-50">
                  <div className="custom-overflow max-h-[90vh] w-full max-w-xl overflow-y-auto rounded-lg bg-boxdark p-6">
                    <div className="mb-4 flex items-center justify-between">
                      <h3 className="text-lg font-medium">Download Songs</h3>
                      <button onClick={() => setShowDownloadModal(false)}>
                        <FontAwesomeIcon icon="fa-solid fa-times" />
                      </button>
                    </div>

                    <div className="space-y-4">
                      {/* ID Range */}
                      <div className="rounded border border-strokedark p-4">
                        <h4 className="mb-3 text-sm font-medium">
                          By ID Range
                        </h4>
                        <div className="grid grid-cols-2 gap-4">
                          <div>
                            <label className="mb-2 block text-xs">
                              Start ID
                            </label>
                            <input
                              type="text"
                              placeholder="YYYY-N"
                              className={`w-full rounded border ${
                                downloadFilters.id_range.start &&
                                !isValidIdFormat(downloadFilters.id_range.start)
                                  ? "border-danger"
                                  : "border-strokedark"
                              } bg-boxdark px-3 py-2`}
                              value={downloadFilters.id_range.start}
                              onChange={(e) => {
                                const value = e.target.value;
                                setDownloadFilters((prev) => ({
                                  ...prev,
                                  id_range: {
                                    ...prev.id_range,
                                    start: value,
                                    array: generateIdRange(
                                      value,
                                      prev.id_range.end
                                    ),
                                  },
                                }));
                              }}
                            />
                            {downloadFilters.id_range.start &&
                              !isValidIdFormat(
                                downloadFilters.id_range.start
                              ) && (
                                <p className="mt-1 text-xs text-danger">
                                  Please use format: YYYY-N (e.g., 2324-112)
                                </p>
                              )}
                          </div>
                          <div>
                            <label className="mb-2 block text-xs">End ID</label>
                            <input
                              type="text"
                              placeholder="YYYY-N"
                              className={`w-full rounded border ${
                                downloadFilters.id_range.end &&
                                !isValidIdFormat(downloadFilters.id_range.end)
                                  ? "border-danger"
                                  : "border-strokedark"
                              } bg-boxdark px-3 py-2`}
                              value={downloadFilters.id_range.end}
                              onChange={(e) => {
                                const value = e.target.value;
                                setDownloadFilters((prev) => ({
                                  ...prev,
                                  id_range: {
                                    ...prev.id_range,
                                    end: value,
                                    array: generateIdRange(
                                      prev.id_range.start,
                                      value
                                    ),
                                  },
                                }));
                              }}
                            />
                            {downloadFilters.id_range.end &&
                              !isValidIdFormat(
                                downloadFilters.id_range.end
                              ) && (
                                <p className="mt-1 text-xs text-danger">
                                  Please use format: YYYY-N (e.g., 2324-400)
                                </p>
                              )}
                          </div>
                        </div>
                        {/* Preview of generated range */}
                        {downloadFilters.id_range.array?.length > 0 && (
                          <div className="mt-2">
                            <p className="text-xs text-meta-5">
                              Generated range (
                              {downloadFilters.id_range.array.length} IDs):
                              <span className="ml-1 text-meta-6">
                                {downloadFilters.id_range.array
                                  .slice(0, 3)
                                  .join(", ")}
                                {downloadFilters.id_range.array.length > 3 &&
                                  "..."}
                                {downloadFilters.id_range.array.length > 3 &&
                                  downloadFilters.id_range.array[
                                    downloadFilters.id_range.array.length - 1
                                  ]}
                              </span>
                            </p>
                          </div>
                        )}
                      </div>

                      {/* Mix Date Range */}
                      <div className="rounded border border-strokedark p-4">
                        <h4 className="mb-3 text-sm font-medium">
                          By Mix Date Range
                        </h4>
                        <div className="grid grid-cols-2 gap-4">
                          <div>
                            <label className="mb-2 block text-xs">
                              Start Date
                            </label>
                            <SingleDatePicker
                              id="mixDateStart"
                              date={
                                dates.mixDateStart
                                  ? moment(dates.mixDateStart)
                                  : null
                              }
                              onDateChange={(date) => {
                                setDates((prev) => ({
                                  ...prev,
                                  mixDateStart: date,
                                }));
                                setDownloadFilters({
                                  ...downloadFilters,
                                  mix_date_range: {
                                    ...downloadFilters.mix_date_range,
                                    start: date
                                      ? date.format("YYYY-MM-DD")
                                      : null,
                                  },
                                });
                              }}
                              focused={focusedInput.mixDateStart}
                              onFocusChange={({ focused }) =>
                                setFocusedInput((prev) => ({
                                  ...prev,
                                  mixDateStart: focused,
                                }))
                              }
                              numberOfMonths={1}
                              isOutsideRange={() => false}
                              displayFormat="MM-DD-YYYY"
                              placeholder="Select Start Date"
                              readOnly={true}
                              customInputIcon={null}
                              noBorder={true}
                              block
                            />
                          </div>
                          <div>
                            <label className="mb-2 block text-xs">
                              End Date
                            </label>
                            <SingleDatePicker
                              id="mixDateEnd"
                              date={
                                dates.mixDateEnd
                                  ? moment(dates.mixDateEnd)
                                  : null
                              }
                              onDateChange={(date) => {
                                setDates((prev) => ({
                                  ...prev,
                                  mixDateEnd: date,
                                }));
                                setDownloadFilters({
                                  ...downloadFilters,
                                  mix_date_range: {
                                    ...downloadFilters.mix_date_range,
                                    end: date
                                      ? date.format("YYYY-MM-DD")
                                      : null,
                                  },
                                });
                              }}
                              focused={focusedInput.mixDateEnd}
                              onFocusChange={({ focused }) =>
                                setFocusedInput((prev) => ({
                                  ...prev,
                                  mixDateEnd: focused,
                                }))
                              }
                              numberOfMonths={1}
                              isOutsideRange={() => false}
                              displayFormat="MM-DD-YYYY"
                              placeholder="Select End Date"
                              readOnly={true}
                              customInputIcon={null}
                              noBorder={true}
                              block
                            />
                          </div>
                        </div>
                      </div>

                      {/* Personnel Selection */}
                      <div className="rounded border border-strokedark p-4">
                        <h4 className="mb-3 text-sm font-medium">
                          By Personnel
                        </h4>
                        <div className="space-y-3">
                          <div>
                            <label className="mb-2 block text-xs">Writer</label>
                            <select
                              className="w-full rounded border border-strokedark bg-boxdark px-3 py-2"
                              value={downloadFilters.writer_id}
                              onChange={(e) =>
                                setDownloadFilters({
                                  ...downloadFilters,
                                  writer_id: e.target.value,
                                })
                              }
                            >
                              <option value="">Select Writer</option>
                              {writers.map((writer) => (
                                <option key={writer.id} value={writer.id}>
                                  {writer.name}
                                </option>
                              ))}
                            </select>
                          </div>
                          <div>
                            <label className="mb-2 block text-xs">Artist</label>
                            <select
                              className="w-full rounded border border-strokedark bg-boxdark px-3 py-2"
                              value={downloadFilters.artist_id}
                              onChange={(e) =>
                                setDownloadFilters({
                                  ...downloadFilters,
                                  artist_id: e.target.value,
                                })
                              }
                            >
                              <option value="">Select Artist</option>
                              {artists.map((artist) => (
                                <option key={artist.id} value={artist.id}>
                                  {artist.name}
                                </option>
                              ))}
                            </select>
                          </div>
                          <div>
                            <label className="mb-2 block text-xs">
                              Engineer
                            </label>
                            <select
                              className="w-full rounded border border-strokedark bg-boxdark px-3 py-2"
                              value={downloadFilters.engineer_id}
                              onChange={(e) =>
                                setDownloadFilters({
                                  ...downloadFilters,
                                  engineer_id: e.target.value,
                                })
                              }
                            >
                              <option value="">Select Engineer</option>
                              {engineers.map((engineer) => (
                                <option key={engineer.id} value={engineer.id}>
                                  {engineer.name}
                                </option>
                              ))}
                            </select>
                          </div>
                        </div>
                      </div>
                    </div>

                    <div className="mt-6 flex justify-end gap-2">
                      <button
                        className="rounded bg-danger px-4 py-2 text-white"
                        onClick={() => setShowDownloadModal(false)}
                      >
                        Cancel
                      </button>
                      <button
                        className="rounded bg-meta-7 px-4 py-2 text-white"
                        onClick={() => {
                          setDownloadFilters({
                            id_range: { start: "", end: "", array: [] },
                            mix_date_range: { start: "", end: "" },
                            writer_id: "",
                            artist_id: "",
                            engineer_id: "",
                          });
                          handleBulkDownload();
                        }}
                      >
                        Download All
                      </button>
                      <button
                        className="rounded bg-success px-4 py-2 text-white"
                        onClick={handleBulkDownload}
                      >
                        Download Filtered
                      </button>
                    </div>
                  </div>
                </div>
              )}
            </div>

            {isMoveModeActive ? (
              <div className="flex items-center gap-2">
                <button
                  type="button"
                  className={`inline-flex h-9 items-center justify-center rounded ${
                    selectedSongsForMove.length > 0
                      ? "bg-success"
                      : "bg-gray-500"
                  } px-4 py-2 text-sm font-medium text-white hover:bg-opacity-90`}
                  onClick={() => setShowMoveModal(true)}
                  disabled={selectedSongsForMove.length === 0}
                >
                  Move ({selectedSongsForMove.length})
                </button>
                <button
                  type="button"
                  className="inline-flex h-9 items-center justify-center rounded bg-danger px-4 py-2 text-sm font-medium text-white hover:bg-opacity-90"
                  onClick={() => {
                    setIsMoveModeActive(false);
                    setSelectedSongsForMove([]);
                  }}
                >
                  <FontAwesomeIcon
                    icon="fa-solid fa-times"
                    className="h-3 w-3"
                  />
                </button>
              </div>
            ) : (
              <button
                type="button"
                className="inline-flex h-9 items-center justify-center rounded bg-primary px-4 py-2 text-sm font-medium text-white hover:bg-opacity-90"
                onClick={handleMoveClick}
              >
                Move
              </button>
            )}
            <button
              type="button"
              className="inline-flex h-9 items-center justify-center rounded bg-primary px-4 py-2 text-sm font-medium text-white hover:bg-opacity-90"
              onClick={() => setShowAddSongModal(true)}
            >
              +
            </button>
          </div>
        </div>

        <div className="mb-4 border-b border-strokedark px-4 py-4 sm:px-6 2xl:px-9 dark:border-strokedark">
          <form className="">
            <div>
              <div className="flex items-center gap-3">
                {/* Mix Season */}
                <div className="flex w-64 flex-col">
                  <CustomSelect2
                    value={filters.mix_season_id}
                    className="h-[36px] w-full rounded border-[1.5px] border-form-strokedark bg-form-input px-3 py-2 text-sm outline-none transition placeholder:font-normal placeholder:text-bodydark focus:border-primary active:border-primary disabled:cursor-default disabled:bg-whiter dark:border-form-strokedark dark:bg-form-input dark:focus:border-primary"
                    onChange={(value) => {
                      setFilters((prev) => ({
                        ...prev,
                        mix_season_id: value,
                      }));
                    }}
                    label="Select Mix Season"
                  >
                    <option value="">Mix Season</option>
                    {mixSeasons.map((item) => (
                      <option key={item.id} value={item.id}>
                        {item.name}
                      </option>
                    ))}
                  </CustomSelect2>
                </div>

                {/* Song Title */}
                <div className="flex w-64 flex-col">
                  <input
                    type="text"
                    placeholder="Search Song Title"
                    value={filters.type_name}
                    className="h-[36px] w-full rounded border-[1.5px] border-form-strokedark bg-form-input px-3 py-2 text-sm outline-none transition placeholder:font-normal placeholder:text-bodydark focus:border-primary active:border-primary disabled:cursor-default disabled:bg-whiter dark:border-form-strokedark dark:bg-form-input dark:focus:border-primary"
                    onChange={(e) => {
                      setFilters((prev) => ({
                        ...prev,
                        type_name: e.target.value,
                      }));
                    }}
                  />
                </div>

                {/* Lyrics */}
                <div className="flex w-64 flex-col">
                  <div className="relative">
                    <input
                      type="text"
                      placeholder="Search lyrics..."
                      value={lyricsSearch}
                      onChange={(e) => handleLyricsSearch(e.target.value)}
                      className="h-[36px] w-full rounded border-[1.5px] border-form-strokedark bg-form-input px-3 py-2 text-sm outline-none transition placeholder:font-normal placeholder:text-bodydark focus:border-primary active:border-primary disabled:cursor-default disabled:bg-whiter dark:border-form-strokedark dark:bg-form-input dark:focus:border-primary"
                    />
                    {lyricsSearch && (
                      <button
                        onClick={() => {
                          setLyricsSearch("");
                          handleLyricsSearch("");
                        }}
                        className="absolute right-2 top-1/2 -translate-y-1/2 text-gray-400 hover:text-white"
                      >
                        <FontAwesomeIcon icon="fa-solid fa-times" />
                      </button>
                    )}
                  </div>
                </div>
              </div>
              {/* Action Buttons */}
              <div className="mt-4 flex items-center gap-2">
                <button
                  type="button"
                  onClick={(e) => handleFilterData(e)}
                  className="inline-flex items-center justify-center rounded-md bg-primary px-4 py-2 text-sm font-medium text-white hover:bg-opacity-90"
                >
                  Search
                </button>
                <button
                  onClick={resetForm}
                  type="button"
                  className="inline-flex items-center justify-center rounded-md border border-strokedark bg-danger px-4 py-2 text-sm font-medium text-white hover:bg-opacity-90"
                >
                  Reset
                </button>
              </div>
            </div>
          </form>
        </div>

        <div>
          <div className="custom-overflow overflow-x-auto">
            <table
              id="unassigned-songs-container"
              ref={tableContainerRef}
              className="w-full table-auto"
            >
              <thead className="bg-meta-4">
                <tr>
                  {columns.map((column, i) => {
                    if (column.accessor == "select") {
                      return (
                        <th className="relative whitespace-nowrap px-3 py-3 text-left text-xs font-medium uppercase tracking-wider text-bodydark1"></th>
                      );
                    }
                    return (
                      <th
                        key={i}
                        className="relative whitespace-nowrap px-3 py-3 text-left text-xs font-medium uppercase tracking-wider text-bodydark1"
                      >
                        <div className="flex items-center gap-2">
                          {column.header}
                          {column.accessor !== "actions" &&
                            column.accessor !== "status" &&
                            column.accessor !== "assigned_to" &&
                            column.accessor !== "edit" && (
                              <div className="relative">
                                <button
                                  ref={(el) =>
                                    (filterButtonRefs[column.accessor] = el)
                                  }
                                  onClick={() =>
                                    handleFilterMenuClick(column.accessor)
                                  }
                                  className="hover:text-primary"
                                >
                                  <FontAwesomeIcon
                                    icon="fa-solid fa-filter"
                                    className={`h-3 w-3 ${
                                      isFilterActive(column.accessor)
                                        ? "text-primary"
                                        : ""
                                    }`}
                                  />
                                </button>

                                {showFilterMenu === column.accessor && (
                                  <div
                                    ref={filterMenuRef}
                                    data-filter-menu={column.accessor}
                                    className={`absolute z-50 max-h-[400px] min-w-[200px] rounded-lg bg-boxdark shadow-lg`}
                                  >
                                    {renderFilterContent(column.accessor)}
                                  </div>
                                )}
                              </div>
                            )}
                        </div>
                      </th>
                    );
                  })}
                </tr>
              </thead>
              {loading ? (
                <tbody className="text-white">
                  {" "}
                  <tr s>
                    {" "}
                    <td colSpan={columns.length}>
                      <div className="flex items-center justify-center py-10">
                        <ClipLoader color="#fff" size={20} className="mr-3" />
                        <span className="text-xl font-medium text-white">
                          Loading...
                        </span>
                      </div>
                    </td>
                  </tr>
                </tbody>
              ) : (
                <tbody className="text-white">
                  {filteredData.map((row, i) => {
                    // Find employees by type
                    const writer = row.employees?.find(
                      (emp) => emp.emp_type === "writer"
                    );
                    console.log(row.employees, "sjns");

                    const artist = row.employees?.find(
                      (emp) => emp.emp_type === "artist"
                    );
                    console.log(artist, "ndbdb");
                    const engineer = row.employees?.find(
                      (emp) => emp.emp_type === "engineer"
                    );
                    let statusStr = "N/A";
                    if (row.workorder_status) {
                      statusMapping.forEach((item) => {
                        if (Number(item.id) === Number(row.workorder_status)) {
                          statusStr = item.name;
                        }
                      });
                    }

                    if (
                      row.workorder_id &&
                      row.workorder_status &&
                      row.writer_submit_status &&
                      row.workorder_artist_id === row.workorder_engineer_id
                    ) {
                      statusStr = "Artist/Engineer";
                    }

                    //

                    if (
                      row.workorder_id &&
                      row.workorder_status &&
                      row.workorder_auto_approve === 1 &&
                      row.workorder_writer_id === row.workorder_artist_id
                    ) {
                      if (row.workorder_status === 1) {
                        statusStr = "Writer/Artist";
                      } else if (row.workorder_status === 5) {
                        statusStr = "Completed";
                      }
                    }

                    if (
                      row.workorder_id &&
                      row.workorder_status &&
                      row.workorder_auto_approve === 1 &&
                      row.workorder_writer_id === row.workorder_artist_id &&
                      row.workorder_writer_id === row.workorder_engineer_id
                    ) {
                      if (row.workorder_status === 1) {
                        statusStr = "Wri/Art/Eng";
                      } else if (row.workorder_status === 5) {
                        statusStr = "Completed";
                      }
                    }

                    if (row.workorder_status === 5) {
                      statusStr = "Completed";
                    }

                    if (row.type.includes("Upload")) {
                      statusStr = "Completed";
                    }
                    // Transform the data to match the expected structure
                    const transformedRow = {
                      id: row.id,
                      searchTerm: lyricsSearch,
                      id_string: row.id_string,
                      mix_date: row.create_at,
                      title: row.type_name,
                      song_key: row.song_key,
                      type_name: row.type_name,
                      bpm: row.bpm,
                      writer_id: writer?.id,
                      writer_cost: writer?.emp_cost,
                      artist_id: artist?.id,
                      artist_cost: artist?.emp_cost,
                      engineer_id: engineer?.id,
                      engineer_cost: engineer?.emp_cost,
                      project_name: row.project_name,
                      team_name: row.team_name,
                      gender: row.gender,
                      status: statusStr,
                      lyrics: row.lyrics,
                      genre: row.genre,
                      project_id: row.project_id,
                      song_type: row.song_type,
                      notes: row.notes,
                      admin_writer_instrumentals:
                        row.admin_writer_instrumentals,
                      masters: row.masters,
                      assigned: row.assigned,
                      idea_str: row.idea_str,
                      is_file: row.is_file,
                      workorder_id: row.workorder_id,
                      workorder_status: row.workorder_status,
                      // Add any other fields needed by your SongTableRow component
                    };

                    return (
                      <SongTableRow
                        key={i}
                        handleAddIdeaForMultiSubProject={
                          handleAddIdeaForMultiSubProject
                        }
                        ideas={ideas}
                        callDataAgain={callDataAgain}
                        row={transformedRow}
                        setSelectedSongsForMove={setSelectedSongsForMove}
                        selectedSongsForMove={selectedSongsForMove}
                        isMoveModeActive={isMoveModeActive}
                        columns={columns}
                        handleFileUpload={handleFileUpload}
                        handleAssignIdea={handleAssignIdea}
                        handleAddIdea={handleAddIdea}
                        handleUpdateField={handleUpdateField}
                        handleEmployeeChange={handleEmployeeChange}
                        handleResetEmployee={handleResetEmployee}
                        writers={writers} // Use the actual writers from state
                        artists={artists} // Use the actual artists from state
                        engineers={engineers} // Use the actual engineers from state
                        handleProjectAssignment={handleProjectAssignment}
                        projects={projects}
                      />
                    );
                  })}
                </tbody>
              )}
            </table>
          </div>
          <div className="p-5">
            <PaginationBar
              currentPage={currentPage}
              pageCount={pageCount}
              pageSize={pageSize}
              canPreviousPage={canPreviousPage}
              canNextPage={canNextPage}
              updatePageSize={updatePageSize}
              previousPage={previousPage}
              nextPage={nextPage}
              dataTotal={dataTotal}
              callDataAgain={callDataAgain}
              setCurrentPage={setPage}
            />
          </div>
        </div>
      </div>

      {showReassignModal && (
        <ReassignSongModal
          projects={projects}
          setModalClose={handleReassignSongModalClose}
          setSelectedReassignProjectId={handleReassignSong}
        />
      )}

      {showAddSongModal && (
        <AddSongModal
          isOpen={showAddSongModal}
          mixSeasons={mixSeasons}
          setIsOpen={setShowAddSongModal}
          onSubmit={handleAddSong}
          artists={artists}
          writers={writers}
          engineers={engineers}
        />
      )}

      {showEditSongModal && (
        <EditSongModal
          isOpen={showEditSongModal}
          setIsOpen={setShowEditSongModal}
          onSubmit={handleEditSong}
          songData={selectedSongForEdit}
        />
      )}

      {showMoveModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-50">
          <div className="w-full max-w-md rounded-lg bg-boxdark p-6">
            <div className="mb-4 flex items-center justify-between">
              <h3 className="text-lg font-medium">Move Songs to Mix Season</h3>
              <button onClick={() => setShowMoveModal(false)}>
                <FontAwesomeIcon icon="fa-solid fa-times" />
              </button>
            </div>
            <div className="mb-4">
              <CustomSelect2
                className="w-full rounded border border-strokedark bg-boxdark px-3 py-2"
                value={selectedMixSeason}
                onChange={(value) => setSelectedMixSeason(value)}
                label="Select Mix Season"
              >
                <option value="">Select Mix Season</option>
                {mixSeasons.map((season) => (
                  <option key={season.id} value={season.id}>
                    {season.name}
                  </option>
                ))}
              </CustomSelect2>
            </div>
            <div className="flex justify-end gap-2">
              <button
                className="rounded bg-danger px-4 py-2 text-white"
                onClick={() => setShowMoveModal(false)}
              >
                Cancel
              </button>
              <button
                className="rounded bg-success px-4 py-2 text-white"
                onClick={handleMoveSongs}
              >
                Confirm Move
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default ListUnAssignedSongsPage;
