import React, { useEffect } from "react";
import { jsPDF } from "jspdf";
import moment from "moment";
import { useLocation, useNavigate, useParams } from "react-router-dom";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { AuthContext, tokenExpireError } from "Src/authContext";
import { GlobalContext, showToast } from "Src/globalContext";
import {
  getSurveyByProjectIdAndUuidAPI,
  deleteProjectAPI,
  updateProjectAPI,
  getProjectDetailsManagerAPI,
  getProjectDetailsAdminAPI,
  updateSubProjectDetailsAPI,
} from "Src/services/projectService";
import { getAllEmployeeByGroupAPI } from "Src/services/employeeService";
import {
  addSubProjectAPI,
  getSubProjectsByProjectIdAPI,
  deleteSubProjectsAPI,
  getAllIdeaAPI,
  addIdeaAPI,
  updateIdeaAPI,
  deleteOneFileAPI,
  getAllSubProjectIdeaAPI,
  assignSubProjectIdeasAPI,
  deleteSubProjectIdeaAPI,
  getSurveyByProjectIdAPI,
  updateSubProjectStatusAPI,
  getAllLyricsByProjectIdAPI,
  updateSubProjectEightCountAPI,
  updateSubProjectEmployeeAPI,
  updateSubProjectEmployeeCostAPI,
  getAllMasterFilesByProjectIdAPI,
  resetSubProjectEmployeeAPI,
  addAndAssignIdeaToMultiSubProjectsAPI,
} from "Src/services/projectService";
import {
  updateLyricsPublicAPI,
  deleteS3FileAPI,
  uploadS3FilesAPI,
} from "Src/services/workOrderService";
import {
  sendEmailAPIV3,
  getOneEmailBySlugAPI,
} from "Src/services/emailService";
import { getUserDetailsByIdAPI } from "Src/services/userService";
import {
  getSurveyDetails,
  updateSurveyThemeOfTheRoutineAPI,
} from "Src/services/surveyService";
import {
  uuidv4,
  sortSubProjectsAscByTypeName,
  countSubProjectsByType,
  calculateManagementDiscount,
  calculateNetTotal,
  stringFormatToLimitedChar,
  filterEightCountValues,
  generateHtmlString,
  sortByStringAsc,
  downloadAsZipFilesByWebLinks,
  copyLinkToClipboard,
  replaceBrTagToNextLine,
  validateUuidv4,
  sortSeasonAsc,
  removeKeysWhenValueIsNull,
} from "Utils/utils";
import SubProjects from "Components/ViewProject/SubProjects/SubProjects";
import AddSubProject from "Components/ViewProject/SubProjects/AddSubProject";
import AddTracking from "Components/ViewProject/Tracking/AddTracking";
import Idea from "Components/ViewProject/Idea/Idea";
import AssignIdea from "Components/ViewProject/Idea/AssignIdea";
import ResendSurvey from "Components/ViewProject/ResendSurvey/ResendSurvey";
import ConfirmModal from "Components/Modal/ConfirmModal";
import Spinner from "Components/Spinner";
// import AddIdeaForMultiSubProjectModal from 'Components/AddIdeaForMultiSubProjectModal';
import ClientMediaTabs from "Components/Client/ClientViewProjectDetails/ClientMediaTabs";
import { Portal } from "@headlessui/react";
import ClientEightCountTab from "Components/Client/ClientViewProjectDetails/ClientEightCountTab";
import ClientSurveyTab from "Components/Client/ClientViewProjectDetails/ClientSurveyTab";
import ClientMusicDetailsTab from "Components/Client/ClientViewProjectDetails/ClientMusicDetailsTab";
import ChooseDateToReLockSurvey from "Components/ChooseSurveyDateReLock";
import DuoConfirmModal from "Components/Modal/DuoConfirmModal";
import License from "Components/License";
import {
  addMediaAPI,
  retrieveAllMediaAPI,
} from "Src/services/clientProjectDetailsService";
import html2canvas from "html2canvas";
import { retrieveAllMixSeasonsAPI } from "Src/services/mixSeasonService";
import { retrieveAllSettingsAPI } from "Src/services/settingService";
import AddIdeaForMultiSubProjectModal from "Components/AddIdeaForMultiSubProjectMasterModal";
import JSZip from "jszip";
import { createDownloadProgressBox } from "Utils/downloadProgress";
import CustomSelect2 from "Components/CustomSelect2";

const BASE_URL = "https://equalityrecords.com/";

const AdminViewProjectPage = () => {
  const navigate = useNavigate();

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

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

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

  const [surveySubmitStatus, setSurveySubmitStatus] = React.useState(false);
  const [lockDate, setLockDate] = React.useState("");
  const [viewModel, setViewModel] = React.useState({});
  const [user_id, setUserId] = React.useState(null);
  const [surveyLink, setSurveyLink] = React.useState("");
  const [settings, setSettings] = React.useState([]);
  const [projectTotal, setProjectTotal] = React.useState(0);
  const [managementDiscount, setManagementDiscount] = React.useState(0);
  const [colorsT, setColorsT] = React.useState(null);
  const [netTotal, setNetTotal] = React.useState(0);
  const [isSubProject, setIsSubProject] = React.useState(false);
  const [isIdea, setIsIdea] = React.useState(false);
  const [addTypeName, setAddTypeName] = React.useState("");
  const [writers, setWriters] = React.useState([]);
  const [artists, setArtists] = React.useState([]);
  const [engineers, setEngineers] = React.useState([]);
  const [producers, setProducers] = React.useState([]);
  const [addSelectedWriter, setAddSelectedWriter] = React.useState({});
  const [addSelectedArtist, setAddSelectedArtist] = React.useState({});
  const [addSelectedEngineer, setAddSelectedEngineer] = React.useState({});
  const [addSelectedProducer, setAddSelectedProducer] = React.useState({});
  const [addWriterCost, setAddWriterCost] = React.useState(0);
  const [addArtistCost, setAddArtistCost] = React.useState(0);
  const [addEngineerCost, setAddEngineerCost] = React.useState(0);
  const [addProducerCost, setAddProducerCost] = React.useState(0);
  const [addTotalCost, setAddTotalCost] = React.useState(0);
  const [submittedIdeas, setSubmittedIdeas] = React.useState([]);
  const [mixSeasons, setMixSeasons] = React.useState([]);

  const [deleteItemId, setDeleteItemId] = React.useState(null);
  const [showDeleteProjectModal, setShowDeleteProjectModal] =
    React.useState(false);

  const [subProjects, setSubProjects] = React.useState([]);
  const [ideas, setIdeas] = React.useState([]);

  const [addVoiceoverUI, setAddVoiceoverUI] = React.useState(false);
  const [addSongUI, setAddSongUI] = React.useState(false);
  const [addTrackingUI, setAddTrackingUI] = React.useState(false);
  const [showResendSurveyModal, setShowResendSurveyModal] =
    React.useState(false);

  const [selectedSubProjectId, setSelectedSubProjectId] = React.useState(null);
  const [assignedIdeas, setAssignedIdeas] = React.useState([]);

  const [showAssignIdeaModal, setShowAssignIdeaModal] = React.useState(false);

  const [voiceCount, setVoiceCount] = React.useState(0);
  const [songCount, setSongCount] = React.useState(0);
  const [trackingCount, setTrackingCount] = React.useState(0);
  const [tempVoiceCount, setTempVoiceCount] = React.useState(0);
  const [tempSongCount, setTempSongCount] = React.useState(0);
  const [tempTrackingCount, setTempTrackingCount] = React.useState(0);
  const [disableVoiceoverBtn, setDisableVoiceoverBtn] = React.useState(false);
  const [disableSongBtn, setDisableSongBtn] = React.useState(false);
  const [disableTrackingBtn, setDisableTrackingBtn] = React.useState(false);

  const [voiceOverEightCount, setVoiceOverEightCount] = React.useState(0);
  const [songEightCount, setSongEightCount] = React.useState(0);
  const [trackingEightCount, setTrackingEightCount] = React.useState(0);

  const [userCompanyName, setUserCompanyName] = React.useState("");
  const [programName, setProgramName] = React.useState("");
  const [teamName, setTeamName] = React.useState("");

  const [showRealProjectModal, setShowRealProjectModal] = React.useState(false);
  const [expandAll, setExpandAll] = React.useState(false);

  const [isEdit, setIsEdit] = React.useState(false);
  const [selectedSubProjectIdsForDelete, setSelectedSubProjectIdsForDelete] =
    React.useState([]);
  const [showActionMenu, setShowActionMenu] = React.useState(false);
  const [emailHtmlBody, setEmailHtmlBody] = React.useState("");
  const [emailTags, setEmailTags] = React.useState([]);
  const [emailSubject, setEmailSubject] = React.useState("");

  const [showExpressDownloadButtons, setShowExpressDownloadButtons] =
    React.useState(false);

  const [showAddIdeaModal, setShowAddIdeaModal] = React.useState(false);
  const [enableEditThemeOfTheRoutine, setEnableEditThemeOfTheRoutine] =
    React.useState(false);
  const [themeOfTheRoutine, setThemeOfTheRoutine] = React.useState("");
  const [isMedia, setIsMedia] = React.useState(false);
  const [isEightCount, setIsEightCount] = React.useState(false);
  const [isTeamDetails, setIsTeamDetails] = React.useState(false);
  const [isSurvey, setIsSurvey] = React.useState(false);
  const [uploadCount, setUploadCount] = React.useState(0);
  const [tempUploadCount, setTempUploadCount] = React.useState(0);

  const [paymentStatus, setPaymentStatus] = React.useState(
    viewModel?.payment_status || null
  );

  const [SubscriptionType, setSubscriptionType] = React.useState(null);

  // Add filter states
  const [selectedClientIds, setSelectedClientIds] = React.useState([]);
  const [selectedTeamNames, setSelectedTeamNames] = React.useState([]);
  const [selectedMixTypeIds, setSelectedMixTypeIds] = React.useState([]);
  const [mixDateStart, setMixDateStart] = React.useState("");
  const [mixDateEnd, setMixDateEnd] = React.useState("");

  const loadFiltersFromStorage = () => {
    try {
      const clientIds = localStorage.getItem("AdminProjectClientId");
      const teamNames = localStorage.getItem("AdminProjectTeamName");
      const mixTypeIds = localStorage.getItem("AdminProjectMixTypeId");
      const startDate = localStorage.getItem("AdminProjectMixDateStart");
      const endDate = localStorage.getItem("AdminProjectMixDateEnd");

      setSelectedClientIds(clientIds ? JSON.parse(clientIds) : []);
      setSelectedTeamNames(teamNames ? JSON.parse(teamNames) : []);
      setSelectedMixTypeIds(mixTypeIds ? JSON.parse(mixTypeIds) : []);
      setMixDateStart(startDate || "");
      setMixDateEnd(endDate || "");

      return {
        client_ids: clientIds
          ? JSON.parse(clientIds).map((c) => c.value)
          : null,
        team_names: teamNames
          ? JSON.parse(teamNames).map((t) => t.value)
          : null,
        mix_type_ids: mixTypeIds
          ? JSON.parse(mixTypeIds).map((m) => m.value)
          : null,
        mix_date_start: startDate || null,
        mix_date_end: endDate || null,
      };
    } catch (error) {
      console.error("Error loading filters:", error);
      return {};
    }
  };

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

  React.useEffect(() => {
    setPaymentStatus(viewModel.payment_status);
  }, [viewModel]);

  const params = useParams();

  const handleEditClick = (e) => {
    e.preventDefault();
    setIsEdit(!isEdit);
  };

  const handleShowAddIdeaModal = () => {
    setShowAddIdeaModal(true);
  };

  const handleHideAddIdeaModal = () => {
    setShowAddIdeaModal(false);
  };

  const handleRealProjectModalClose = () => {
    setShowRealProjectModal(false);
  };

  const openSecondDelete = () => {
    setShowDeleteProjectModal(false);

    setTimeout(() => {
      setShowRealProjectModal(true);
    }, 500);
  };

  const handleAddIdeaForMultiSubProject = async (data) => {
    try {
      //
      setShowAddIdeaModal(false);
      const payload = {
        project_id: Number(params?.id),
        subproject_ids: data.subproject_ids,
      };

      const result = await addAndAssignIdeaToMultiSubProjectsAPI(payload);

      if (!result.error) {
        showToast(globalDispatch, result.message, 5000);
        window.location.reload();
      } else {
        showToast(globalDispatch, result.message, 5000, "error");
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  const getProjectDetails = async (filters = {}) => {
    try {
      const result = await getProjectDetailsAdminAPI(
        Number(params?.id),
        removeKeysWhenValueIsNull({ ...filters })
      );
      if (!result.error) {
        console.log(result.model);

        if (!result.model) {
          showToast(globalDispatch, "Access Denied", 5000, "error");
          navigate("/admin/projects");
          return;
        }
        setViewModel(result.model);
        setUserId(result.model.user_id);
        setProjectTotal(result.model?.total);
        setProgramName(result.model.program_name);
        setTeamName(result.model.team_name);
        setThemeOfTheRoutine(result.model?.theme_of_the_routine);
        await retrieveAllSettings(
          result.model?.total,
          result.model.discount,
          result.model.expenses,
          result.model.user_id
        );
      } else {
        showToast(globalDispatch, result.message, 5000, "error");
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  const getOneEmailBySlug = async () => {
    try {
      const result = await getOneEmailBySlugAPI("survey");

      //
      if (!result.error) {
        setEmailSubject(result.model.subject);
        setEmailHtmlBody(result.model.html);
        // detect comma is present in tags string
        let tags = [];
        if (result.model.tag.includes(",")) {
          tags = result.model.tag.split(",");
        } else {
          tags.push(result.model.tag);
        }
        setEmailTags(tags);
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

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

        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 getSubProjectsByProjectId = async () => {
    try {
      const filters = loadFiltersFromStorage();
      const result = await getSubProjectsByProjectIdAPI(
        Number(params?.id),
        filters
      );
      if (!result.error) {
        if (result.list.length > 0) {
          let sortedSubProjects = sortSubProjectsAscByTypeName(result.list);
          setSubProjects(sortedSubProjects);
          let count = countSubProjectsByType(sortedSubProjects);
          setVoiceCount(count.voiceCount);
          setSongCount(count.songCount);
          setTrackingCount(count.trackingCount);
          setTempVoiceCount(count.voiceCount);
          setTempSongCount(count.songCount);
          setTempTrackingCount(count.trackingCount);
          setUploadCount(count.uploadCount);
          setTempUploadCount(count.uploadCount);
        } else {
          setTempUploadCount(0);
          setUploadCount(0);
          setSubProjects([]);
          setVoiceCount(0);
          setSongCount(0);
          setTrackingCount(0);
          setTempVoiceCount(0);
          setTempSongCount(0);
          setTempTrackingCount(0);
        }
      } else {
        showToast(globalDispatch, result.message, 5000, "error");
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  useEffect(() => {
    (async function () {
      await getSubProjectsByProjectId();
    })();
  }, [subproject_update]);

  const handleLoadIdeaByProjectId = async () => {
    await getAllIdeasByProjectId();
  };

  const getAllIdeasByProjectId = async () => {
    try {
      const result = await getAllIdeaAPI(Number(params?.id));
      if (!result.error) {
        setIdeas(result.list);
      } else {
        showToast(globalDispatch, result.message, 5000, "error");
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  const handleSelectedSubProjectId = async (subProjectId) => {
    if (subProjectId) {
      setSelectedSubProjectId(Number(subProjectId));
      const result = await getAllSubProjectIdeaAPI(Number(subProjectId));
      if (!result.error) {
        setAssignedIdeas(result.list);
        globalDispatch({
          type: "SET_ASSIGNED_IDEAS",
          payload: result.list,
        });
      } else {
        showToast(globalDispatch, result.message, 5000, "error");
      }
    } else {
      setSelectedSubProjectId(null);
    }
  };

  const handleSelectedSubProjectIdForDelete = (subProjectId) => {
    setSelectedSubProjectIdsForDelete((prev) => [...prev, subProjectId]);
  };

  const handleUnSelectedSubProjectIdForDelete = (subProjectId) => {
    setSelectedSubProjectIdsForDelete((prev) =>
      prev.filter((item) => item !== subProjectId)
    );
  };

  const handleDeleteSubProjects = async (e) => {
    try {
      e.preventDefault();
      if (selectedSubProjectIdsForDelete.length === 0) {
        showToast(
          globalDispatch,
          "Please select at least one sub project",
          3000,
          "error"
        );
        return;
      }

      const payload = {
        subproject_ids: selectedSubProjectIdsForDelete,
      };

      const result = await deleteSubProjectsAPI(payload);

      if (!result.error) {
        showToast(globalDispatch, result.message, 5000);
        // setSelectedSubProjectIdsForDelete([]);
        // await getSubProjectsByProjectId();
        // await getAllEmployeeByGroup();
        // await getAllIdeasByProjectId();
        // setIsEdit(false);
        window.location.reload();
      } else {
        showToast(globalDispatch, result.message, 5000, "error");
        setSelectedSubProjectIdsForDelete([]);
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  const handleAddVoiceoverBtnClick = () => {
    setAddVoiceoverUI(true);
    setDisableVoiceoverBtn(!disableVoiceoverBtn);
    setDisableSongBtn(true);
    setDisableTrackingBtn(true);
    setTempVoiceCount(tempVoiceCount + 1);
  };

  const handleAddSongBtnClick = () => {
    setAddSongUI(true);
    setDisableVoiceoverBtn(true);
    setDisableSongBtn(!disableSongBtn);
    setDisableTrackingBtn(true);
    setTempSongCount(tempSongCount + 1);
  };

  const handleAddTrackingBtnClick = () => {
    setAddTrackingUI(true);
    setDisableVoiceoverBtn(true);
    setDisableSongBtn(true);
    setDisableTrackingBtn(!disableTrackingBtn);
    setTempTrackingCount(tempTrackingCount + 1);
  };

  const handleHideAddSubProject = () => {
    setAddVoiceoverUI(false);
    setAddSongUI(false);
    setAddTrackingUI(false);
    setDisableVoiceoverBtn(false);
    setDisableSongBtn(false);
    setDisableTrackingBtn(false);
    setTempVoiceCount(voiceCount);
    setTempSongCount(songCount);
    setTempTrackingCount(trackingCount);
  };

  const handleShowResendModalClose = () => {
    setShowResendSurveyModal(false);
  };

  const handleShowAssignIdeaModalClose = () => {
    setShowAssignIdeaModal(false);
  };

  const handleShowAssignIdeaModalOpen = () => {
    setShowAssignIdeaModal(true);
  };

  const retrieveAllSettings = async (total, discount, expenses, user) => {
    try {
      const filterKeywords = [
        "management_value",
        "management_value_type",
        "voiceover_eight_count",
        "song_eight_count",
        "tracking_eight_count",
      ];
      const result = await retrieveAllSettingsAPI({ user_id: user });
      if (!result.error) {
        console.log(result);
        if (result.list.length === 0) {
          showToast(
            globalDispatch,
            "Member settings is not updated",
            4000,
            "error"
          );
          // navigate(`/${authState.role}/setting`);
        }
        let filteredResult = result.list.filter((item) =>
          filterKeywords.includes(item.setting_key)
        );
        setSettings(filteredResult);
        let totalWithDiscount = Number(total) - Number(discount);
        let mgtDiscountObj = calculateManagementDiscount(
          filteredResult,
          totalWithDiscount
        );
        let managementDiscount = Number(mgtDiscountObj.managementDiscountVal);
        setManagementDiscount(managementDiscount);
        let netTotal = calculateNetTotal(
          totalWithDiscount,
          managementDiscount,
          Number(expenses)
        );
        setNetTotal(netTotal);

        let eightCountObj = filterEightCountValues(filteredResult);
        setVoiceOverEightCount(eightCountObj.voiceoverEightCount);
        setSongEightCount(eightCountObj.songEightCount);
        setTrackingEightCount(eightCountObj.trackingEightCount);
      } else {
        showToast(globalDispatch, "Please update your settings", 4000, "error");
        navigate(`/${authState.role}/setting`);
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  const getSurveyByProjectId = async (id) => {
    try {
      const result = await getSurveyByProjectIdAPI(id);
      if (!result.error) {
        setSurveyLink(BASE_URL + "survey/" + result.model.uuidv4);
        if (result.model.status === 1) {
          setSurveySubmitStatus(true);
        } else {
          setSurveySubmitStatus(false);
        }
      } else {
        showToast(globalDispatch, result.message, 5000, "error");
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  const getUserDetails = async (userId) => {
    try {
      const result = await getUserDetailsByIdAPI(userId);
      if (!result.error) {
        setUserCompanyName(result.model?.company_name);
        setSubscriptionType(result?.model?.subscription);
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

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

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

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

  const companyName = localStorage.getItem("companyName");

  async function handleUploadLicense(id) {
    try {
      const input = document.querySelector(`#printable-component-`);
      const p = document.querySelector("#pop");

      const canvas = await html2canvas(input, {
        allowTaint: true,
        useCors: true,
        logging: true,
        proxy: viewModel?.company_info?.license_company_logo || "",
      });

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

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

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

      const result = await uploadS3FilesAPI(formData);

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

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

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

    let mixSeasonName = viewModel.mix_season_name;
    const isLicense =
      result?.list.find(
        (elem) => elem.description == shortenYearRange(mixSeasonName)
      ) || null;

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

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

      await handleUploadLicense(id);
      const emailResult =
        parseInt(SubscriptionType) !== 1 && (await sendEmailAPIV3(payloade));
    }
  };

  const updateProjectsPaymentStatus = async (status) => {
    try {
      setIsLoading(true);
      const promises = await updateProjectAPI({
        id: params?.id,
        discount: viewModel?.discount,
        payment_status: parseInt(status),
      });

      if (!promises.error) {
        await LicenseMail(
          status,
          params?.id,
          viewModel.payment_status,
          viewModel.team_name,
          viewModel.program_name,
          viewModel.program_owner_email,
          viewModel?.mix_season_id
        );

        await getProjectDetails(loadFiltersFromStorage());
        showToast(
          globalDispatch,
          "Project status updated successfully",
          4000,
          "success"
        );
      }

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

  const handleResendSurvey = async () => {
    try {
      let uuidv4Code = uuidv4();
      const payload = {
        uuidv4: uuidv4Code,
        project_id: Number(params?.id),
      };
      const surveyRes = await getSurveyByProjectIdAndUuidAPI(payload);
      if (!surveyRes.error) {
        const surveyLink = `https://equalityrecords.com/survey/${surveyRes.model.uuidv4}`;

        const emailData = {
          program_name: programName,
          company_name: userCompanyName,
          team_name: teamName,
          link: surveyLink,
        };

        let subject = generateHtmlString(emailSubject, emailData, emailTags);
        let body = generateHtmlString(emailHtmlBody, emailData, emailTags);

        const payload = {
          from: "myeq@equalityrecords.com",
          to: viewModel?.program_owner_email,
          subject,
          body,
        };

        const result = await sendEmailAPIV3(payload);

        if (!result.error) {
          showToast(globalDispatch, result.message, 5000);
          setShowResendSurveyModal(false);
        } else {
          showToast(globalDispatch, result.message, 5000, "error");
          setShowResendSurveyModal(false);
        }
      } else {
        showToast(globalDispatch, surveyRes.message, 5000, "error");
        setShowResendSurveyModal(false);
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  const handleAddWriterChange = (e) => {
    e.preventDefault();
    if (e.target.value === "") {
      setAddSelectedWriter({});
      setAddWriterCost(0);
      setAddTotalCost(
        0 +
          Number(addArtistCost) +
          Number(addEngineerCost) +
          Number(addProducerCost)
      );
      return;
    }
    const writer = writers.find((x) => x.id === Number(e.target.value));
    if (writer && writer.is_writer) {
      setAddSelectedWriter(writer);
      setAddWriterCost(Number(writer?.writer_cost));
      setAddTotalCost(
        Number(writer?.writer_cost) +
          Number(addArtistCost) +
          Number(addEngineerCost) +
          Number(addProducerCost)
      );
    } else {
      setAddSelectedWriter({});
      setAddWriterCost(0);
      setAddTotalCost(
        Number(writer?.writer_cost) +
          Number(addArtistCost) +
          Number(addEngineerCost) +
          Number(addProducerCost)
      );
    }
  };

  const handleAddArtistChange = (e) => {
    e.preventDefault();
    if (e.target.value === "") {
      setAddSelectedArtist({});
      setAddArtistCost(0);
      setAddTotalCost(
        Number(addWriterCost) +
          0 +
          Number(addEngineerCost) +
          Number(addProducerCost)
      );
      return;
    }
    const artist = artists.find((x) => x.id === Number(e.target.value));
    if (artist && artist.is_artist) {
      setAddSelectedArtist(artist);
      setAddArtistCost(Number(artist?.artist_cost));
      setAddTotalCost(
        Number(addWriterCost) +
          Number(artist?.artist_cost) +
          Number(addEngineerCost) +
          Number(addProducerCost)
      );
    } else {
      setAddSelectedArtist({});
      setAddArtistCost(0);
      setAddTotalCost(
        Number(addWriterCost) +
          Number(artist?.artist_cost) +
          Number(addEngineerCost) +
          Number(addProducerCost)
      );
    }
  };

  const handleAddEngineerChange = (e) => {
    e.preventDefault();
    if (e.target.value === "") {
      setAddSelectedEngineer({});
      setAddEngineerCost(0);
      setAddTotalCost(
        Number(addWriterCost) +
          Number(addArtistCost) +
          0 +
          Number(addProducerCost)
      );
      return;
    }
    const engineer = engineers.find((x) => x.id === Number(e.target.value));
    if (engineer && engineer.is_engineer) {
      setAddSelectedEngineer(engineer);
      setAddEngineerCost(Number(engineer?.engineer_cost));
      setAddTotalCost(
        Number(addWriterCost) +
          Number(addArtistCost) +
          Number(engineer?.engineer_cost) +
          Number(addProducerCost)
      );
    } else {
      setAddSelectedEngineer({});
      setAddEngineerCost(0);
      setAddTotalCost(
        Number(addWriterCost) +
          Number(addArtistCost) +
          Number(engineer?.engineer_cost) +
          Number(addProducerCost)
      );
    }
  };

  const handleAddProducerChange = (e) => {
    e.preventDefault();
    if (e.target.value === "") {
      setAddSelectedProducer({});
      setAddProducerCost(0);
      setAddTotalCost(
        Number(addWriterCost) +
          Number(addArtistCost) +
          Number(addEngineerCost) +
          0
      );
      return;
    }
    const producer = producers.find((x) => x.id === Number(e.target.value));
    if (producer && producer.is_producer) {
      setAddSelectedProducer(producer);
      setAddProducerCost(Number(producer?.producer_cost));
      setAddTotalCost(
        Number(addWriterCost) +
          Number(addArtistCost) +
          Number(addEngineerCost) +
          Number(producer?.producer_cost)
      );
    } else {
      setAddSelectedProducer({});
      setAddProducerCost(0);
      setAddTotalCost(
        Number(addWriterCost) +
          Number(addArtistCost) +
          Number(addEngineerCost) +
          Number(producer?.producer_cost)
      );
    }
  };

  const handleAddWriterCostChange = (e) => {
    e.preventDefault();
    if (e.target.value === "") {
      setAddWriterCost(0);
      setAddTotalCost(
        0 +
          Number(addArtistCost) +
          Number(addEngineerCost) +
          Number(addProducerCost)
      );
      return;
    }

    setAddWriterCost(Number(e.target.value));
    setAddTotalCost(
      Number(e.target.value) +
        Number(addArtistCost) +
        Number(addEngineerCost) +
        Number(addProducerCost)
    );
  };

  const handleAddArtistCostChange = (e) => {
    e.preventDefault();
    if (e.target.value === "") {
      setAddArtistCost(0);
      setAddTotalCost(
        Number(addWriterCost) +
          0 +
          Number(addEngineerCost) +
          Number(addProducerCost)
      );
      return;
    }

    setAddArtistCost(Number(e.target.value));
    setAddTotalCost(
      Number(addWriterCost) +
        Number(e.target.value) +
        Number(addEngineerCost) +
        Number(addProducerCost)
    );
  };

  const handleAddEngineerCostChange = (e) => {
    e.preventDefault();
    if (e.target.value === "") {
      setAddEngineerCost(0);
      setAddTotalCost(
        Number(addWriterCost) +
          Number(addArtistCost) +
          0 +
          Number(addProducerCost)
      );
      return;
    }

    setAddEngineerCost(Number(e.target.value));
    setAddTotalCost(
      Number(addWriterCost) +
        Number(addArtistCost) +
        Number(e.target.value) +
        Number(addProducerCost)
    );
  };

  const handleAddProducerCostChange = (e) => {
    e.preventDefault();
    if (e.target.value === "") {
      setAddProducerCost(0);
      setAddTotalCost(
        Number(addWriterCost) +
          Number(addArtistCost) +
          Number(addEngineerCost) +
          0
      );
      return;
    }

    setAddProducerCost(Number(e.target.value));
    setAddTotalCost(
      Number(addWriterCost) +
        Number(addArtistCost) +
        Number(addEngineerCost) +
        Number(e.target.value)
    );
  };

  const handleUpdateIdea = async (payload) => {
    try {
      if (payload) {
        const result = await updateIdeaAPI(payload);
        if (!result.error) {
          showToast(globalDispatch, result.message, 5000, "success");
          await getAllIdeasByProjectId();
        } else {
          showToast(globalDispatch, result.message, 5000, "error");
        }
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  const location = useLocation();

  const handleAddIdea = async (payload) => {
    try {
      if (payload) {
        let ideaPayload = {
          ...payload,
          project_id: Number(params?.id),
        };
        const result = await addIdeaAPI(ideaPayload);
        if (!result.error) {
          showToast(globalDispatch, result.message, 5000, "success");
          await getAllIdeasByProjectId();
          // window.location.reload();
        } else {
          showToast(globalDispatch, result.message, 5000, "error");
        }
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  const handleSubProjectClick = () => {
    setIsSubProject(true);
    setIsIdea(false);
    setIsMedia(false);
    setIsEightCount(false);
    setIsSurvey(false);
    setIsTeamDetails(false);
  };

  const handleIdeaClick = () => {
    setIsSubProject(false);
    setIsIdea(true);
    setIsMedia(false);
    setIsEightCount(false);
    setIsSurvey(false);
    setIsTeamDetails(false);
  };

  const handleMediaClick = () => {
    setIsMedia(true);
    setIsIdea(false);
    setIsSubProject(false);
    setIsEightCount(false);
    setIsSurvey(false);
    setIsTeamDetails(false);
  };

  const handleTeamDetailsClick = () => {
    setIsMedia(false);
    setIsIdea(false);
    setIsSubProject(false);
    setIsEightCount(false);
    setIsSurvey(false);
    setIsTeamDetails(true);
  };
  const handleEightCountClick = () => {
    setIsMedia(false);
    setIsIdea(false);
    setIsSubProject(false);
    setIsEightCount(true);
    setIsSurvey(false);
    setIsTeamDetails(false);
  };
  const handleSurveyClick = () => {
    setIsMedia(false);
    setIsIdea(false);
    setIsSubProject(false);
    setIsEightCount(false);
    setIsSurvey(true);
    setIsTeamDetails(false);
  };

  React.useEffect(() => {
    const tab = localStorage.getItem("AdminSelectedTab");
    if (!tab) {
      if (parseInt(SubscriptionType) == 1 || parseInt(SubscriptionType) == 3) {
        handleSubProjectClick();
      } else {
        handleTeamDetailsClick();

        //  setIsTeamDetails(true);
      }
    } else {
      tab == 1 && handleIdeaClick();
      tab == 2 && handleSubProjectClick();
      tab == 3 && handleTeamDetailsClick();
      tab == 4 && handleEightCountClick();
      tab == 5 && handleMediaClick();
    }
  }, [location.pathname]);

  const tab = localStorage.getItem("AdminSelectedTab");

  React.useEffect(() => {
    if (parseInt(SubscriptionType) == 3) {
      !tab && handleSubProjectClick();
      tab == 1 && handleIdeaClick();
      tab == 2 && handleSubProjectClick();
      tab == 3 && handleTeamDetailsClick();
      tab == 4 && handleEightCountClick();
      tab == 5 && handleMediaClick();
    } else if (parseInt(SubscriptionType) == 1) {
      tab == 1 && handleIdeaClick();
      tab == 2 && handleSubProjectClick();
      (tab == 3 || tab == 4 || tab == 5) && handleSubProjectClick();
    } else {
      console.log(SubscriptionType);
      console.log("pp");
      tab == 1 && handleTeamDetailsClick();
      !tab && handleTeamDetailsClick();

      //  setIsTeamDetails(true);
    }
  }, [location.pathname, SubscriptionType, tab]);

  const handleAddTypeChange = (type) => {
    setAddTypeName(type);
  };

  const handleAddSubProject = async (e) => {
    try {
      e.preventDefault();

      let employees = [];

      let writer = {};
      let artist = {};
      let engineer = {};
      let producer = {};

      if (addSelectedWriter?.id) {
        writer = {
          id: addSelectedWriter?.id,
          type: addSelectedWriter?.is_writer ? "writer" : "",
          cost: Number(addWriterCost),
        };
        if (writer.id) {
          employees.push(writer);
        }
      }
      if (addSelectedArtist?.id) {
        artist = {
          id: addSelectedArtist?.id,
          type: addSelectedArtist?.is_artist ? "artist" : "",
          cost: Number(addArtistCost),
        };
        if (artist.id) {
          employees.push(artist);
        }
      }
      if (addSelectedEngineer?.id) {
        engineer = {
          id: addSelectedEngineer?.id,
          type: addSelectedEngineer?.is_engineer ? "engineer" : "",
          cost: Number(addEngineerCost),
        };
        if (engineer.id) {
          employees.push(engineer);
        }
      }
      if (addSelectedProducer?.id) {
        producer = {
          id: addSelectedProducer?.id,
          type: addSelectedProducer?.is_producer ? "producer" : "",
          cost: Number(addProducerCost),
        };
        if (producer.id) {
          employees.push(producer);
        }
      }

      if (!addTypeName) {
        showToast(
          globalDispatch,
          "Please enter sub project type name",
          5000,
          "error"
        );
        return;
      }

      // addTypeName could be Voiceover 1, Voiceover 2, Song 1, Song 2, Tracking 1, Tracking 2
      // if matches with Voiceover then we take voiceOverEightCount

      let localEightCount = 0;
      if (addTypeName.toLowerCase().includes("voiceover")) {
        localEightCount = voiceOverEightCount;
      } else if (addTypeName.toLowerCase().includes("tracking")) {
        localEightCount = trackingEightCount;
      } else {
        localEightCount = songEightCount;
      }

      const payload = {
        type_name: addTypeName,
        project_id: Number(params?.id),
        eight_count: Number(localEightCount),
        employees,
        is_song: addTypeName.toLowerCase().includes("song") ? 1 : 0,
      };

      // setIsLoading(true);
      const result = await addSubProjectAPI(payload);
      if (!result.error) {
        handleHideAddSubProject();
        showToast(globalDispatch, result.message, 5000);
        await retrieveAllSettings(
          viewModel?.total,
          viewModel?.discount,
          viewModel?.expenses,
          viewModel?.user_id
        );
        await getProjectDetails(loadFiltersFromStorage());
        await getSubProjectsByProjectId();
        await getAllIdeasByProjectId();
        await getAllEmployeeByGroup();
        // await getAllProjectFiles();
        await getSurveyByProjectId(Number(params?.id));
        // setIsLoading(false);
      } else {
        showToast(globalDispatch, result.message, 5000, "error");
        return;
        // setIsLoading(false);
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  const updateSubProject = async (payload) => {
    try {
      const result = await updateSubProjectDetailsAPI(payload);
      if (!result.error) {
        handleHideAddSubProject();
        showToast(globalDispatch, result.message, 5000);
        // await retrieveAllSettings(
        //   viewModel?.total,
        //   viewModel?.discount,
        //   viewModel?.expenses
        // );
        await getProjectDetails(loadFiltersFromStorage());
        await getSubProjectsByProjectId();
        await getAllIdeasByProjectId();
        await getAllEmployeeByGroup();
        // await getAllProjectFiles();
        await getSurveyByProjectId(Number(params?.id));
        // setIsLoading(false);
      } else {
        showToast(globalDispatch, result.message, 5000, "error");
        return;
        // setIsLoading(false);
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  React.useEffect(() => {
    getAllIdeasByProjectId();
  }, [isIdea]);

  const handleIncompleteSubProject = async (subProjectId) => {
    try {
      // setIsLoading(true);
      const payload = {
        subproject_id: Number(subProjectId),
        status: 0,
      };
      const result = await updateSubProjectStatusAPI(payload);
      if (!result.error) {
        showToast(globalDispatch, result.message, 5000);
        await retrieveAllSettings(
          viewModel?.total,
          viewModel?.discount,
          viewModel?.expenses,
          viewModel?.user_id
        );
        await getProjectDetails(loadFiltersFromStorage());
        await getSubProjectsByProjectId();
        await getAllIdeasByProjectId();
        await getAllEmployeeByGroup();
        // await getAllProjectFiles();
        await getSurveyByProjectId(Number(params?.id));
      } else {
        showToast(globalDispatch, result.message, 5000, "error");
        return;
      }
      // setIsLoading(false);
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  const handleDownloadAllLyrics = async () => {
    try {
      const result = await getAllLyricsByProjectIdAPI(Number(params?.id));
      if (!result.error) {
        if (result.list.length > 0) {
          const doc = new jsPDF();
          let pageNumber = 1;
          const pageHeight = doc.internal.pageSize.height;
          let yPosition = 10;

          result.list.forEach((item, index) => {
            const teamName = item.team_name;
            const programName = item.program_name;

            // check only for <br> tag and only if </br> tag exists then replace with \n
            if (item.lyrics) item.lyrics = replaceBrTagToNextLine(item.lyrics);

            const lyrics = `Type: ${item.type_name}\nLyrics:\n${
              item.lyrics ? item.lyrics : "N/A"
            }`;

            const textHeight = doc.getTextDimensions(lyrics).h;

            if (yPosition + textHeight > pageHeight - 10) {
              // If the content doesn't fit on the current page, add a new page
              doc.addPage();
              pageNumber++;
              yPosition = 10;
            }

            // Split the text into smaller chunks to fit the page
            const textChunks = doc.splitTextToSize(
              lyrics,
              doc.internal.pageSize.width - 20
            );
            textChunks.forEach((chunk) => {
              doc.text(10, yPosition, chunk);
              yPosition += doc.getTextDimensions(chunk).h + 10; // Add space between items
              if (yPosition + textHeight > pageHeight - 10) {
                doc.addPage();
                pageNumber++;
                yPosition = 10;
              }
            });

            // Add extra space between items
            yPosition += 20;

            if (index === result.list.length - 1) {
              doc.save(
                `${teamName}_${programName}_${moment().format(
                  "HH:mm:ss_DD-MM-YYYY"
                )}_Page_${pageNumber}.pdf`
              );
            }
          });
        }
      } else {
        showToast(globalDispatch, result.message, 5000, "error");
        return;
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  const handleDownloadMasterFiles = async () => {
    try {
      const result = await getAllMasterFilesByProjectIdAPI(Number(params?.id));
      if (!result.error) {
        if (result.list.length > 0) {
          const zipFileName = `Project_${programName}_${teamName}_master_files_${moment().format(
            "HH:mm:ss_DD-MM-YYYY"
          )}`;

          // Initialize download manager
          window.downloadManager = window.downloadManager || {
            downloads: new Map(),
            progressBox: null,
          };

          if (!window.downloadManager.progressBox) {
            window.downloadManager.progressBox = createDownloadProgressBox();
          }

          const downloadId = Date.now();
          window.downloadManager.downloads.set(downloadId, {
            fileName: zipFileName,
            progress: 0,
            status: "starting",
            type: "master",
          });

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

          try {
            let linksArr = result.list.map((row) => row.url);
            const totalFiles = linksArr.length;
            let completedFiles = 0;
            let totalProgress = 0;

            // First phase: Download each file (0-80%)
            const promises = linksArr.map(async (link) => {
              const response = await fetch(link);
              if (!response.ok) {
                throw new Error(`Failed to fetch ${link}`);
              }

              const contentLength = response.headers.get("content-length");
              const total = parseInt(contentLength, 10);
              let loaded = 0;

              const reader = response.body.getReader();
              const chunks = [];

              while (true) {
                const { done, value } = await reader.read();
                if (done) break;

                chunks.push(value);
                loaded += value.length;

                // Calculate progress for this file
                const fileProgress = (loaded / total) * 100;
                totalProgress =
                  (completedFiles / totalFiles) * 100 +
                  fileProgress / totalFiles;

                // Update progress (0-80% phase)
                window.downloadManager.downloads.set(downloadId, {
                  fileName: zipFileName,
                  progress: Math.min(Math.round(totalProgress * 0.8), 80),
                  status: "downloading",
                  type: "master",
                });
                window.downloadManager.progressBox.updateDownloads(
                  window.downloadManager.downloads
                );
              }

              completedFiles++;
              return new Blob(chunks);
            });

            const blobs = await Promise.all(promises);

            // Second phase: Create zip (80-100%)
            const zip = new JSZip();
            blobs.forEach((blob, index) => {
              const fileName = linksArr[index].split("/").pop();
              zip.file(fileName, blob);
            });

            const zipBlob = await zip.generateAsync({
              type: "blob",
              onUpdate: (metadata) => {
                // Convert zip progress (0-100) to overall progress (80-100)
                const zipProgress = 80 + (metadata.percent || 0) * 0.2;
                window.downloadManager.downloads.set(downloadId, {
                  fileName: zipFileName,
                  progress: Math.round(zipProgress),
                  status: "downloading",
                  type: "master",
                });
                window.downloadManager.progressBox.updateDownloads(
                  window.downloadManager.downloads
                );
              },
            });

            // Create download link
            const zipLink = document.createElement("a");
            zipLink.href = URL.createObjectURL(zipBlob);
            zipLink.download = `${zipFileName}.zip`;
            zipLink.click();
            URL.revokeObjectURL(zipLink.href);

            // Mark as complete
            window.downloadManager.downloads.set(downloadId, {
              fileName: zipFileName,
              progress: 100,
              status: "complete",
              type: "master",
            });
            window.downloadManager.progressBox.updateDownloads(
              window.downloadManager.downloads
            );

            // Cleanup after delay
            setTimeout(() => {
              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);

            showToast(
              globalDispatch,
              "Master Files Downloaded Successfully",
              5000
            );
          } catch (error) {
            window.downloadManager.downloads.set(downloadId, {
              fileName: zipFileName,
              progress: 0,
              status: "failed",
              type: "master",
            });
            window.downloadManager.progressBox.updateDownloads(
              window.downloadManager.downloads
            );
            showToast(
              globalDispatch,
              "Error downloading master files",
              5000,
              "error"
            );
          }
        } else {
          showToast(globalDispatch, "No master files found", 5000, "error");
        }
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  const handleAssignIdea = async (ids) => {
    try {
      const payload = {
        subproject_id: selectedSubProjectId,
        idea_ids: ids,
      };
      const result = await assignSubProjectIdeasAPI(payload);
      if (!result.error) {
        showToast(globalDispatch, result.message, 5000);
        await retrieveAllSettings(
          viewModel?.total,
          viewModel?.discount,
          viewModel?.expenses,
          viewModel?.user_id
        );
        await getProjectDetails(loadFiltersFromStorage());
        await getSubProjectsByProjectId();
        await getAllIdeasByProjectId();
        await getAllEmployeeByGroup();
        // await getAllProjectFiles();
        await getSurveyByProjectId(Number(params?.id));
        const subProjectIdeasResult = await getAllSubProjectIdeaAPI(
          Number(selectedSubProjectId)
        );
        if (!subProjectIdeasResult.error) {
          setAssignedIdeas(subProjectIdeasResult.list);
        } else {
          showToast(
            globalDispatch,
            subProjectIdeasResult.message,
            5000,
            "error"
          );
        }
        handleShowAssignIdeaModalClose();
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  const handleExpandAll = () => {
    setExpandAll(!expandAll);
  };

  const copyLinkToClipboardTrigger = (link) => {
    try {
      const result = copyLinkToClipboard(link);
      if (result) {
        showToast(globalDispatch, "Link copied to clipboard", 3000, "info");
      } else {
        showToast(globalDispatch, "Copy failed", 3000, "error");
      }
    } catch (error) {
      console.error(error);
      showToast(globalDispatch, "Copy failed", 3000, "error");
    }
  };

  const handleDeleteProjectModalClose = () => {
    setShowDeleteProjectModal(false);
  };

  const handleDeleteProject = async () => {
    try {
      const result = await deleteProjectAPI(deleteItemId);
      if (!result.error) {
        setShowDeleteProjectModal(false);
        navigate(`/${authState.role}/projects`);
        showToast(globalDispatch, result.message, 4000);
      } else {
        setShowDeleteProjectModal(false);
        showToast(globalDispatch, result.message, 4000, "error");
      }
    } catch (err) {
      showToast(globalDispatch, err.message, 4000, "error");
      setShowDeleteProjectModal(false);
      tokenExpireError(dispatch, err.message);
    }
  };

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

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

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

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

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

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

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

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

  const handleUpdateLyrics = async (payload) => {
    try {
      const result = await updateLyricsPublicAPI(payload);
      if (!result.error) {
        showToast(globalDispatch, "Lyrics updated successfully", 5000);
        await getSubProjectsByProjectId();
        return;
      } else {
        showToast(globalDispatch, result.message, 5000, "error");
        return;
      }
    } catch (error) {
      showToast(globalDispatch, error.message, 5000, "error");
    }
  };

  const handleDeleteSubProjectIdea = async (payload) => {
    try {
      const result = await deleteSubProjectIdeaAPI(payload);
      if (!result.error) {
        showToast(globalDispatch, result.message, 5000);
        await getSubProjectsByProjectId();
        await getAllIdeasByProjectId();
        const subProjectIdeasResult = await getAllSubProjectIdeaAPI(
          Number(payload.subproject_id)
        );
        if (!subProjectIdeasResult.error) {
          setAssignedIdeas(subProjectIdeasResult.list);
        } else {
          showToast(
            globalDispatch,
            subProjectIdeasResult.message,
            5000,
            "error"
          );
        }
        return;
      } else {
        showToast(globalDispatch, result.message, 5000, "error");
        return;
      }
    } catch (error) {
      showToast(globalDispatch, error.message, 5000, "error");
    }
  };

  const handleDeleteFileSubmit = async (id) => {
    try {
      const result = await deleteOneFileAPI(id);
      if (!result.error) {
        if (result.file) {
          const s3delRes = await deleteS3FileAPI(result.file.url);
          if (!s3delRes.error) {
            showToast(globalDispatch, result.message, 5000);
            window.location.reload();
          }
        }
      } else {
        showToast(globalDispatch, result.message, 5000, "error");
      }
    } catch (error) {
      showToast(globalDispatch, error.message, 5000, "error");
    }
  };

  const handleUpdateThemeOfTheRoutine = async (e) => {
    try {
      e.preventDefault();
      const result = await updateSurveyThemeOfTheRoutineAPI({
        id: Number(viewModel?.survey_id),
        theme_of_the_routine: themeOfTheRoutine,
      });
      if (!result.error) {
        showToast(globalDispatch, result.message, 5000);
        await getProjectDetails(loadFiltersFromStorage());
      } else {
        showToast(globalDispatch, result.message, 5000, "error");
      }
      setEnableEditThemeOfTheRoutine(false);
      return;
    } catch (err) {
      showToast(globalDispatch, err.message, 5000, "error");
    }
  };

  React.useEffect(() => {
    if (viewModel.user_id) {
      (async function () {
        try {
          const result = await getUserDetailsByIdAPI(viewModel.user_id);

          if (!result?.error) {
            setSubscriptionType(result?.model?.subscription);
          }
        } catch (error) {}
      })();
    }
  }, [viewModel.user_id]);

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

    (async function () {
      try {
        setIsLoading(true);
        const filters = loadFiltersFromStorage();
        await getProjectDetails(filters);
        await getSubProjectsByProjectId();
        await getAllIdeasByProjectId();
        await getAllEmployeeByGroup();
        await getOneEmailBySlug();
        await getAllMixSeasons();
        await getSurveyByProjectId(Number(params?.id));
        setIsLoading(false);
      } catch (error) {
        tokenExpireError(dispatch, error.message);
      }
    })();

    const interval = setInterval(async () => {
      try {
        await getProjectDetails(loadFiltersFromStorage());
      } catch (error) {
        tokenExpireError(dispatch, error.message);
      }
    }, 5000);

    return () => clearInterval(interval);
  }, []);

  // React.useEffect(() => {
  //   const userId = viewModel?.user_id;

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

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

  function convertDateFormat(dateString) {
    // Split the date string into year, month, and day

    if (dateString) {
      var parts = dateString?.split("-");

      // Rearrange the parts into the desired format
      var formattedDate =
        parts[1].padStart(2, "0") +
        "-" +
        parts[2].padStart(2, "0") +
        "-" +
        parts[0];

      return formattedDate;
    }
  }

  const [openSurveyDateModal, setOpenSurveyDateModal] = React.useState(false);

  window.addEventListener("beforeunload", async function (event) {
    await localStorage.removeItem("AdminSelectedTab");
  });

  React.useEffect(() => {
    return () => {
      localStorage.removeItem("AdminSelectedTab");
    };
  }, []);

  const hasSubprojectIdeas = ideas.some(
    (obj) => obj.subproject_ideas && obj.subproject_ideas.length > 0
  );

  console.log(isSubProject);
  return (
    <>
      {isLoading ? (
        <>
          <Spinner />
          <License
            id=""
            mixSeasonName={viewModel?.mix_season_name}
            program_owner_name={viewModel?.program_owner_name}
            team_name={viewModel?.team_name}
            program={viewModel?.program_name}
            logo={viewModel?.company_info?.license_company_logo}
            member_name={viewModel?.company_info?.member_name}
            company_name={viewModel?.company_info?.company_name}
          />
        </>
      ) : (
        <div className="max-w-screen w-full bg-boxdark-2 p-5">
          <div className="mx-auto rounded border border-strokedark bg-boxdark p-6">
            {/* Header Navigation Section */}
            <div className="mb-6 flex items-center justify-between">
              <button
                onClick={() => navigate(-1)}
                className="inline-flex items-center justify-center rounded-md bg-meta-4 px-4 py-2 text-sm font-medium text-white hover:bg-opacity-90"
              >
                <FontAwesomeIcon icon="arrow-left" className="mr-2" />
                Back
              </button>

              <div className="flex items-center gap-4">
                {viewModel?.previous_project_id && (
                  <button
                    onClick={() => {
                      window.location.href = `/admin/view-project/${viewModel?.previous_project_id}`;
                    }}
                    className="inline-flex items-center gap-2 text-sm font-medium text-white hover:text-primary"
                  >
                    <FontAwesomeIcon icon="arrow-left" />
                    Previous Project
                  </button>
                )}
                {viewModel?.next_project_id && (
                  <button
                    onClick={() => {
                      window.location.href = `/admin/view-project/${viewModel?.next_project_id}`;
                    }}
                    className="inline-flex items-center gap-2 text-sm font-medium text-white hover:text-primary"
                  >
                    Next Project
                    <FontAwesomeIcon icon="arrow-right" />
                  </button>
                )}
              </div>
            </div>

            {/* Project Title & Actions Section */}
            <div className="mb-6 flex flex-wrap items-center justify-between gap-4">
              <div>
                <h2 className="text-2xl font-semibold text-white">
                  {viewModel?.program_name} - {viewModel?.team_name}
                </h2>
                <p className="mt-1 text-sm font-medium text-bodydark2">
                  Production Date:{" "}
                  {moment(viewModel?.mix_date).format("MM/DD/YYYY")}
                </p>
              </div>

              <div className="flex items-center gap-3">
                <div className="flex items-center gap-2">
                  <ResendSurvey
                    surveySubmitStatus={surveySubmitStatus}
                    ideas={ideas}
                    surveyLink={surveyLink}
                    setShowResendSurveyModal={setShowResendSurveyModal}
                  />
                  <button
                    onClick={() => copyLinkToClipboardTrigger(surveyLink)}
                    className="inline-flex h-9 w-9 items-center justify-center rounded-md bg-primary text-white hover:bg-opacity-90"
                  >
                    <FontAwesomeIcon icon="fa-solid fa-link" />
                  </button>
                  {surveySubmitStatus &&
                    ideas?.length > 0 &&
                    !hasSubprojectIdeas && (
                      <button
                        onClick={() => setOpenSurveyDateModal(true)}
                        className="inline-flex h-9 w-9 items-center justify-center rounded-md bg-primary text-white hover:bg-opacity-90"
                      >
                        <FontAwesomeIcon
                          icon={
                            Date(lockDate) > new Date() ? "lock" : "lock-open"
                          }
                        />
                      </button>
                    )}
                </div>

                {/* 3-dot Menu for Edit/Delete */}

                {/* Subscription Type Select */}
                {parseInt(SubscriptionType) > 1 && (
                  <CustomSelect2
                    value={paymentStatus}
                    onChange={async (value) => {
                      setPaymentStatus(value);
                      await updateProjectsPaymentStatus(value);
                    }}
                    className="rounded-md border border-strokedark bg-boxdark-2/40 px-3 py-2 text-sm font-medium text-white outline-none focus:border-primary"
                  >
                    <option value="" disabled>
                      Payment Status
                    </option>
                    <option value="5">Unpaid</option>
                    <option value="2">Deposit Paid</option>
                    <option value="3">Paid In Full</option>
                    <option value="1">Complete</option>
                    <option value="4">Awaiting Edit</option>
                  </CustomSelect2>
                )}

                <div className="relative">
                  <button
                    onClick={() => setShowActionMenu(!showActionMenu)}
                    className="inline-flex h-9 w-9 items-center justify-center rounded-md border border-strokedark bg-boxdark-2/40 text-white hover:bg-opacity-90"
                  >
                    <FontAwesomeIcon icon="fa-solid fa-ellipsis-vertical" />
                  </button>
                  {showActionMenu && (
                    <div className="shadow-card absolute right-0 top-full z-[9] mt-2 w-40 rounded border border-strokedark bg-boxdark py-1">
                      <button
                        onClick={() => {
                          navigate(
                            `/${authState.role}/edit-project/` + params?.id,
                            {
                              state: params?.id,
                            }
                          );
                        }}
                        className="flex w-full items-center gap-2 px-4 py-2 text-sm font-medium text-white hover:bg-primary/5"
                      >
                        <FontAwesomeIcon icon="fa-solid fa-pen" />
                        Edit
                      </button>
                      <button
                        onClick={() => {
                          setShowDeleteProjectModal(true);
                          setDeleteItemId(params?.id);
                        }}
                        className="flex w-full items-center gap-2 px-4 py-2 text-sm font-medium text-danger hover:bg-primary/5"
                      >
                        <FontAwesomeIcon icon="fa-solid fa-trash" />
                        Delete
                      </button>
                    </div>
                  )}
                </div>
              </div>
            </div>

            {/* Info Cards Grid */}
            <div className="grid grid-cols-1 gap-4 md:grid-cols-2 xl:grid-cols-3">
              {/* Program Owner Card */}
              <div className="rounded border border-strokedark bg-boxdark-2/40 p-4">
                <div className="space-y-3">
                  <div className="flex items-center justify-between">
                    <span className="text-sm text-bodydark2">
                      Program Owner:
                    </span>
                    <span className="text-sm font-medium text-white">
                      {viewModel?.program_owner_name}
                    </span>
                  </div>
                  <div className="flex items-center justify-between">
                    <span className="text-sm text-bodydark2">
                      Program Owner Email:
                    </span>
                    <span className="text-sm font-medium text-white">
                      {viewModel?.program_owner_email}
                    </span>
                  </div>
                  <div className="flex items-center justify-between">
                    <span className="text-sm text-bodydark2">
                      Program Owner Phone:
                    </span>
                    <span className="text-sm font-medium text-white">
                      {viewModel?.program_owner_phone}
                    </span>
                  </div>
                </div>
              </div>

              {/* Project Details Card */}
              <div className="rounded border border-strokedark bg-boxdark-2/40 p-4">
                <div className="space-y-3">
                  <div className="flex items-center justify-between">
                    <span className="text-sm text-bodydark2">Mix Type:</span>
                    <span className="text-sm font-medium text-white">
                      {viewModel?.mix_type_name}
                    </span>
                  </div>
                  <div className="flex items-center justify-between">
                    <span className="text-sm text-bodydark2">Team Type:</span>
                    <span className="text-sm font-medium text-white">
                      {viewModel?.team_type === 1 && "All Girl"}
                      {viewModel?.team_type === 2 && "Co-ed"}
                      {viewModel?.team_type === 3 && "TBD"}
                    </span>
                  </div>
                  <div className="flex items-center justify-between">
                    <span className="text-sm text-bodydark2">Division:</span>
                    <span className="text-sm font-medium text-white">
                      {viewModel?.division}
                    </span>
                  </div>
                </div>
              </div>

              {/* Financial Details Card */}
              <div className="rounded border border-strokedark bg-boxdark-2/40 p-4">
                <div className="space-y-1">
                  <div className="flex items-center justify-between">
                    <span className="text-sm text-bodydark2">Total:</span>
                    <span className="text-sm font-medium text-white">
                      ${Number(viewModel?.total).toFixed(2)}
                    </span>
                  </div>
                  <div className="flex items-center justify-between">
                    <span className="text-sm text-bodydark2">Management:</span>
                    <span className="text-sm font-medium text-white">
                      ${Number(managementDiscount).toFixed(2)}
                    </span>
                  </div>
                  <div className="flex items-center justify-between">
                    <span className="text-sm text-bodydark2">Discount:</span>
                    <span className="text-sm font-medium text-white">
                      ${Number(viewModel?.discount).toFixed(2)}
                    </span>
                  </div>
                  <div className="flex items-center justify-between">
                    <span className="text-sm text-bodydark2">Expenses:</span>
                    <span className="text-sm font-medium text-white">
                      ${Number(viewModel?.expenses).toFixed(2)}
                    </span>
                  </div>
                  <div className="flex items-center justify-between font-medium">
                    <span className="text-sm text-bodydark2">Net Total:</span>
                    <span className="text-sm font-medium text-meta-3">
                      ${netTotal.toFixed(2)}
                    </span>
                  </div>
                </div>
              </div>

              {/* Theme Card */}
              <div className="rounded border border-strokedark bg-boxdark-2/40 p-4">
                <div className="mb-2 flex items-center justify-between">
                  <h4 className="text-sm font-normal text-bodydark2">Theme</h4>
                  {!enableEditThemeOfTheRoutine && (
                    <button
                      onClick={(e) => {
                        e.preventDefault();
                        setEnableEditThemeOfTheRoutine(true);
                      }}
                      className="text-sm text-primary hover:text-opacity-80"
                    >
                      <FontAwesomeIcon icon="fa-solid fa-pen" />
                    </button>
                  )}
                </div>

                {!enableEditThemeOfTheRoutine ? (
                  <p className="text-sm text-white">
                    {stringFormatToLimitedChar(
                      viewModel?.theme_of_the_routine,
                      150
                    )}
                  </p>
                ) : (
                  <div className="flex items-center gap-2">
                    <input
                      type="text"
                      className="w-full rounded border border-strokedark bg-boxdark px-3 py-1 text-sm text-white focus:border-primary"
                      defaultValue={themeOfTheRoutine}
                      onChange={(e) => setThemeOfTheRoutine(e.target.value)}
                    />
                    <button
                      type="button"
                      className="text-meta-3 hover:text-opacity-80"
                      onClick={(e) => handleUpdateThemeOfTheRoutine(e)}
                    >
                      <FontAwesomeIcon icon="fa-solid fa-check" />
                    </button>
                    <button
                      type="button"
                      className="text-danger hover:text-opacity-80"
                      onClick={() => setEnableEditThemeOfTheRoutine(false)}
                    >
                      <FontAwesomeIcon icon="fa-solid fa-xmark" />
                    </button>
                  </div>
                )}
              </div>

              {/* Colors Card */}
              <div className="rounded border border-strokedark bg-boxdark-2/40 p-4">
                <h4 className="mb-4 text-sm font-normal text-bodydark2">
                  Colors
                </h4>
                <div className="flex items-center gap-2 text-sm text-white">
                  {colorsT}
                </div>
              </div>

              {/* Dates Card - Only shown if SubscriptionType > 1 */}
              {parseInt(SubscriptionType) > 1 && (
                <div className="rounded border border-strokedark bg-boxdark-2/40 p-4">
                  <div className="space-y-3">
                    <div className="flex items-center justify-between">
                      <span className="text-sm text-bodydark2">
                        Team Details:
                      </span>
                      <span className="text-sm font-medium text-white">
                        {convertDateFormat(viewModel?.team_details_date)}
                      </span>
                    </div>
                    <div className="flex items-center justify-between">
                      <span className="text-sm text-bodydark2">
                        Routine Submission:
                      </span>
                      <span className="text-sm font-medium text-white">
                        {convertDateFormat(viewModel?.routine_submission_date)}
                      </span>
                    </div>
                    <div className="flex items-center justify-between">
                      <span className="text-sm text-bodydark2">
                        Estimated Delivery:
                      </span>
                      <span className="text-sm font-medium text-white">
                        {convertDateFormat(viewModel?.estimated_delivery_date)}
                      </span>
                    </div>
                  </div>
                </div>
              )}
            </div>
            <section className={`mt-10 w-full`}>
              <div className="mb-0 border-b border-strokedark">
                <div className="flex items-end gap-2 md:items-center">
                  {/* Subscription Type 1 or 3 Buttons */}
                  {parseInt(SubscriptionType) == 1 ||
                  parseInt(SubscriptionType) == 3 ? (
                    <>
                      <button
                        type="button"
                        className={`relative px-4 py-3 text-sm font-medium transition-all md:text-base ${
                          isSubProject
                            ? "text-white before:absolute before:bottom-0 before:left-0 before:h-0.5 before:w-full before:bg-primary"
                            : "text-bodydark2 hover:text-white"
                        }`}
                        onClick={handleSubProjectClick}
                      >
                        <span className="relative z-[5]">Sub Projects</span>
                      </button>
                      <button
                        type="button"
                        className={`relative px-4 py-3 text-sm font-medium transition-all md:text-base ${
                          isIdea
                            ? "text-white before:absolute before:bottom-0 before:left-0 before:h-0.5 before:w-full before:bg-primary"
                            : "text-bodydark2 hover:text-white"
                        }`}
                        onClick={handleIdeaClick}
                      >
                        <span className="relative z-[5]">Survey</span>
                      </button>
                    </>
                  ) : null}

                  {/* Subscription Type > 1 Buttons */}
                  {parseInt(SubscriptionType) > 1 && (
                    <>
                      <button
                        type="button"
                        className={`relative px-4 py-3 text-sm font-medium transition-all md:text-base ${
                          isTeamDetails
                            ? "text-white before:absolute before:bottom-0 before:left-0 before:h-0.5 before:w-full before:bg-primary"
                            : "text-bodydark2 hover:text-white"
                        }`}
                        onClick={handleTeamDetailsClick}
                      >
                        <span className="relative z-[5]">Team Details</span>
                      </button>
                      <button
                        type="button"
                        className={`relative px-4 py-3 text-sm font-medium transition-all md:text-base ${
                          isEightCount
                            ? "text-white before:absolute before:bottom-0 before:left-0 before:h-0.5 before:w-full before:bg-primary"
                            : "text-bodydark2 hover:text-white"
                        }`}
                        onClick={handleEightCountClick}
                      >
                        <span className="relative z-[5]">8-Count</span>
                      </button>
                      <button
                        type="button"
                        className={`relative px-4 py-3 text-sm font-medium transition-all md:text-base ${
                          isMedia
                            ? "text-white before:absolute before:bottom-0 before:left-0 before:h-0.5 before:w-full before:bg-primary"
                            : "text-bodydark2 hover:text-white"
                        }`}
                        onClick={handleMediaClick}
                      >
                        <span className="relative z-[5]">Media</span>
                      </button>
                    </>
                  )}
                </div>
              </div>
              <div className="-24 focus:ring-00 shadow-default w-full rounded border border-form-strokedark bg-form-input p-5 focus-visible:outline-none">
                {isSubProject && (
                  <div className="mb-6 mt-1 flex flex-row flex-nowrap items-center justify-between gap-1 text-white">
                    <div className="flex flex-row justify-start">
                      <buttons
                        type="button"
                        className={`rounded px-2 py-1 ${
                          expandAll
                            ? "bg-yellow-600 hover:bg-yellow-700"
                            : "bg-blue-600 hover:bg-blue-700"
                        }`}
                        onClick={handleExpandAll}
                      >
                        {expandAll ? (
                          <FontAwesomeIcon
                            icon="fa-solid fa-minimize"
                            size="sm"
                          />
                        ) : (
                          <FontAwesomeIcon
                            icon="fa-solid fa-maximize"
                            size="sm"
                          />
                        )}
                      </buttons>
                    </div>

                    <div className="flex flex-row items-center justify-end gap-1">
                      {!isEdit && (
                        <button
                          type="button"
                          className={`rounded-md border border-transparent bg-green-700 px-2 py-1 text-sm font-medium text-white hover:bg-green-800`}
                          onClick={(e) => handleEditClick(e)}
                        >
                          Edit
                        </button>
                      )}
                      {isEdit && (
                        <button
                          type="button"
                          className={`rounded-md border border-transparent bg-blue-600 px-2 py-1 text-sm font-medium text-white hover:bg-blue-700`}
                          onClick={(e) => handleEditClick(e)}
                        >
                          Cancel
                        </button>
                      )}
                      {isEdit && (
                        <button
                          type="button"
                          className={`rounded-md border border-transparent bg-red-500 px-2 py-1 text-sm font-medium text-white hover:bg-red-600`}
                          onClick={(e) => handleDeleteSubProjects(e)}
                        >
                          Delete
                        </button>
                      )}

                      <div
                        className="group relative flex cursor-pointer flex-col items-center rounded bg-blue-500 px-2 py-1.5 hover:bg-blue-600"
                        onClick={(e) => handleShowAddIdeaModal(e)}
                      >
                        <FontAwesomeIcon icon="fa-solid fa-plus" size="sm" />
                        <div className="absolute top-0 mt-8 hidden flex-col items-center group-hover:flex">
                          <span className="whitespace-no-wrap relative z-10 rounded bg-gray-100 p-1 text-center text-xs leading-none text-gray-900 shadow-lg">
                            Assign All Ideas
                          </span>
                        </div>
                      </div>

                      {!disableVoiceoverBtn ? (
                        <div
                          className="group relative flex cursor-pointer flex-col items-center rounded bg-orange-500 px-2 py-1.5 hover:bg-orange-600"
                          onClick={handleAddVoiceoverBtnClick}
                        >
                          <FontAwesomeIcon icon="fa-solid fa-plus" size="sm" />
                          <div className="absolute top-0 mt-8 hidden flex-col items-center group-hover:flex">
                            <span className="whitespace-no-wrap relative z-10 rounded bg-gray-100 p-1 text-center text-xs leading-none text-gray-900 shadow-lg">
                              Add Voiceover
                            </span>
                          </div>
                        </div>
                      ) : (
                        <div
                          className="group relative flex cursor-pointer flex-col items-center rounded bg-gray-500 px-2 py-1.5 hover:bg-gray-600"
                          onClick={handleHideAddSubProject}
                        >
                          <FontAwesomeIcon icon="fa-solid fa-minus" size="sm" />
                          <div className="absolute top-0 mt-8 hidden flex-col items-center group-hover:flex">
                            <span className="whitespace-no-wrap relative z-10 rounded bg-gray-100 p-1 text-center text-xs leading-none text-gray-900 shadow-lg">
                              Add Voiceover
                            </span>
                          </div>
                        </div>
                      )}

                      {!disableSongBtn ? (
                        <div
                          className="group relative flex cursor-pointer flex-col items-center rounded bg-sky-500 px-2 py-1.5 hover:bg-sky-600"
                          onClick={handleAddSongBtnClick}
                        >
                          <FontAwesomeIcon icon="fa-solid fa-plus" size="sm" />
                          <div className="absolute top-0 mt-8 hidden flex-col items-center group-hover:flex">
                            <span className="whitespace-no-wrap relative z-10 rounded bg-gray-100 p-1 text-center text-xs leading-none text-gray-900 shadow-lg">
                              Add Song
                            </span>
                          </div>
                        </div>
                      ) : (
                        <div
                          className="group relative flex cursor-pointer flex-col items-center rounded bg-gray-500 px-2 py-1.5 hover:bg-gray-600"
                          onClick={handleHideAddSubProject}
                        >
                          <FontAwesomeIcon icon="fa-solid fa-minus" size="sm" />
                          <div className="absolute top-0 mt-8 hidden flex-col items-center group-hover:flex">
                            <span className="whitespace-no-wrap relative z-10 rounded bg-gray-100 p-1 text-center text-xs leading-none text-gray-900 shadow-lg">
                              Add Song
                            </span>
                          </div>
                        </div>
                      )}

                      {!disableTrackingBtn ? (
                        <div
                          className="group relative flex cursor-pointer flex-col items-center rounded bg-purple-500 px-2 py-1.5 hover:bg-purple-600"
                          onClick={handleAddTrackingBtnClick}
                        >
                          <FontAwesomeIcon icon="fa-solid fa-plus" size="sm" />
                          <div className="absolute top-0 mt-8 hidden flex-col items-center group-hover:flex">
                            <span className="whitespace-no-wrap relative z-10 rounded bg-gray-100 p-1 text-center text-xs leading-none text-gray-900 shadow-lg">
                              Add Tracking
                            </span>
                          </div>
                        </div>
                      ) : (
                        <div
                          className="group relative flex cursor-pointer flex-col items-center rounded bg-gray-500 px-2 py-1.5 hover:bg-gray-600"
                          onClick={handleHideAddSubProject}
                        >
                          <FontAwesomeIcon icon="fa-solid fa-minus" size="sm" />
                          <div className="absolute top-0 mt-8 hidden flex-col items-center group-hover:flex">
                            <span className="whitespace-no-wrap relative z-10 rounded bg-gray-100 p-1 text-center text-xs leading-none text-gray-900 shadow-lg">
                              Add Tracking
                            </span>
                          </div>
                        </div>
                      )}

                      <div
                        className="group relative flex cursor-pointer flex-col items-center rounded bg-red-500 px-2 py-1.5 hover:bg-red-600"
                        onClick={() =>
                          setShowExpressDownloadButtons(
                            !showExpressDownloadButtons
                          )
                        }
                      >
                        {showExpressDownloadButtons && (
                          <div className="absolute bottom-8 mt-1 flex flex-col items-center group-hover:flex">
                            <button
                              className="whitespace-no-wrap relative z-10 mb-1 flex w-full gap-1 rounded bg-blue-500 px-2 py-1 text-center text-xs leading-none text-white shadow-md hover:bg-blue-600"
                              onClick={handleDownloadAllLyrics}
                              onMouseLeave={() =>
                                setShowExpressDownloadButtons(true)
                              }
                            >
                              <FontAwesomeIcon
                                icon="fa-solid fa-download"
                                size="sm"
                              />
                              Lyrics
                            </button>
                            <button
                              className="whitespace-no-wrap relative z-10 flex w-full gap-1 rounded bg-blue-500 px-2 py-1 text-center text-xs leading-none text-white shadow-md hover:bg-blue-600"
                              onClick={handleDownloadMasterFiles}
                              onMouseLeave={() =>
                                setShowExpressDownloadButtons(true)
                              }
                            >
                              <FontAwesomeIcon
                                icon="fa-solid fa-download"
                                size="sm"
                              />
                              Master Files
                            </button>
                          </div>
                        )}
                        <FontAwesomeIcon
                          icon="fa-solid fa-download"
                          size="sm"
                        />
                      </div>
                    </div>
                  </div>
                )}
                {isSubProject && (
                  <>
                    {addVoiceoverUI && (
                      <AddSubProject
                        typeName={`Voiceover ${tempVoiceCount}`}
                        writers={writers}
                        artists={artists}
                        engineers={engineers}
                        addWriterCost={addWriterCost}
                        addArtistCost={addArtistCost}
                        addEngineerCost={addEngineerCost}
                        addTotalCost={addTotalCost}
                        voiceOverEightCount={voiceOverEightCount}
                        songEightCount={songEightCount}
                        handleAddTypeChange={handleAddTypeChange}
                        handleAddWriterChange={handleAddWriterChange}
                        handleAddArtistChange={handleAddArtistChange}
                        handleAddEngineerChange={handleAddEngineerChange}
                        handleAddSubProject={handleAddSubProject}
                        handleAddWriterCostChange={handleAddWriterCostChange}
                        handleAddArtistCostChange={handleAddArtistCostChange}
                        handleAddEngineerCostChange={
                          handleAddEngineerCostChange
                        }
                      />
                    )}
                    {addSongUI && (
                      <AddSubProject
                        typeName={`Song ${tempSongCount}`}
                        writers={writers}
                        artists={artists}
                        engineers={engineers}
                        addWriterCost={addWriterCost}
                        addArtistCost={addArtistCost}
                        addEngineerCost={addEngineerCost}
                        addTotalCost={addTotalCost}
                        voiceOverEightCount={voiceOverEightCount}
                        songEightCount={songEightCount}
                        handleAddTypeChange={handleAddTypeChange}
                        handleAddWriterChange={handleAddWriterChange}
                        handleAddArtistChange={handleAddArtistChange}
                        handleAddEngineerChange={handleAddEngineerChange}
                        handleAddSubProject={handleAddSubProject}
                        handleAddWriterCostChange={handleAddWriterCostChange}
                        handleAddArtistCostChange={handleAddArtistCostChange}
                        handleAddEngineerCostChange={
                          handleAddEngineerCostChange
                        }
                      />
                    )}
                    {addTrackingUI && (
                      <AddTracking
                        typeName={`Tracking ${tempTrackingCount}`}
                        producers={producers}
                        addTotalCost={addTotalCost}
                        addProducerCost={addProducerCost}
                        handleAddTypeChange={handleAddTypeChange}
                        handleAddProducerChange={handleAddProducerChange}
                        handleAddProducerCostChange={
                          handleAddProducerCostChange
                        }
                        handleAddSubProject={handleAddSubProject}
                      />
                    )}

                    <SubProjects
                      tempUploadCount={tempUploadCount}
                      UploadCount={uploadCount}
                      setTempUploadCount={setTempUploadCount}
                      theme={themeOfTheRoutine}
                      setUpdateSubprojectPayload={updateSubProject}
                      authState={authState}
                      projectId={Number(params?.id)}
                      expandAll={expandAll}
                      isEdit={isEdit}
                      ideas={ideas}
                      writers={writers}
                      artists={artists}
                      engineers={engineers}
                      producers={producers}
                      subProjects={subProjects}
                      expandedSubProjectId={selectedSubProjectId}
                      voiceOverEightCount={voiceOverEightCount}
                      songEightCount={songEightCount}
                      programName={programName}
                      surveySubmitStatus={surveySubmitStatus}
                      setEightCountPayload={handleEightCountChange}
                      setWriterPayload={handleWriterChange}
                      setWriterCostPayload={handleWriterCostChange}
                      setArtistPayload={handleArtistChange}
                      setArtistCostPayload={handleArtistCostChange}
                      setProducerPayload={handleProducerChange}
                      setProducerCostPayload={handleProducerCostChange}
                      setSelectedSubProjectId={handleSelectedSubProjectId}
                      setSelectedSubProjectIdForDelete={
                        handleSelectedSubProjectIdForDelete
                      }
                      setUnSelectedSubProjectIdForDelete={
                        handleUnSelectedSubProjectIdForDelete
                      }
                      setDeleteIdeaPayload={handleDeleteSubProjectIdea}
                      assignedIdeas={assignedIdeas}
                      setLyrics={handleUpdateLyrics}
                      setShowAssignIdeaModal={handleShowAssignIdeaModalOpen}
                      setInCompleteSubProjectId={handleIncompleteSubProject}
                      setDeleteFileId={handleDeleteFileSubmit}
                      setLoadIdeaFromViewProject={handleLoadIdeaByProjectId}
                      setResetWriterPayload={handleResetEmployee}
                      setResetArtistPayload={handleResetEmployee}
                    />
                  </>
                )}
                {isTeamDetails && (
                  <ClientMusicDetailsTab
                    viewModel={viewModel}
                    Team_Date={viewModel?.team_details_date}
                  />
                )}
                {isSurvey && (
                  <ClientSurveyTab
                    survey_id={viewModel?.survey_id}
                    surveyLink={surveyLink}
                    setShowResendSurveyModal={setShowResendSurveyModal}
                  />
                )}
                {isEightCount && (
                  <ClientEightCountTab
                    submittedIdeas={submittedIdeas}
                    viewModel={viewModel}
                    surveyLink={surveyLink}
                  />
                )}
                {isMedia && <ClientMediaTabs viewModel={viewModel} />}

                {isIdea && (
                  <Idea
                    setDeleteIdeaPayload={handleDeleteSubProjectIdea}
                    ideas={ideas}
                    setIdeaAddForm={handleAddIdea}
                    setIdeaUpdateForm={handleUpdateIdea}
                    getAllIdeasByProjectId={getAllIdeasByProjectId}
                  />
                )}
              </div>
            </section>
          </div>
        </div>
      )}

      {openSurveyDateModal && (
        <ChooseDateToReLockSurvey
          setModalClose={setOpenSurveyDateModal}
          id={viewModel?.survey_id}
          lockDate={lockDate}
          viewModel={viewModel}
        />
      )}
      {showResendSurveyModal ? (
        <ConfirmModal
          confirmText={`Are you sure you want to resend the survey?`}
          setModalClose={handleShowResendModalClose}
          setFormYes={handleResendSurvey}
        />
      ) : null}
      {showAssignIdeaModal ? (
        <AssignIdea
          theme={themeOfTheRoutine}
          ideas={ideas}
          assignedIdeas={assignedIdeas}
          setModalClose={handleShowAssignIdeaModalClose}
          setAssignedIdeaForm={handleAssignIdea}
        />
      ) : null}
      {showDeleteProjectModal ? (
        <ConfirmModal
          confirmText={`Are you sure you want to delete this project?`}
          setModalClose={handleDeleteProjectModalClose}
          setFormYes={openSecondDelete}
        />
      ) : null}

      {showRealProjectModal ? (
        <DuoConfirmModal
          confirmText={`Are you sure you want to delete this project? This action cannot be undone.`}
          setModalClose={handleRealProjectModalClose}
          setFormYes={handleDeleteProject}
        />
      ) : null}
      {showAddIdeaModal ? (
        <AddIdeaForMultiSubProjectModal
          subProjects={subProjects}
          setModalClose={handleHideAddIdeaModal}
          setFormYes={handleAddIdeaForMultiSubProject}
        />
      ) : null}
    </>
  );
};

export default AdminViewProjectPage;
