import React from "react";
import { jsPDF } from "jspdf";
import moment from "moment";
import { Link, 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 {
  getProjectDetailsAPI,
  getSurveyByProjectIdAndUuidAPI,
  deleteProjectAPI,
} 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,
} 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,
  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/AddIdeaForMultiSubProjectMasterModal";
import { Tab } from "@headlessui/react";
import ClientEightCountTab from "Components/Client/ClientViewProjectDetails/ClientEightCountTab";
import ClientMediaTabs from "Components/Client/ClientViewProjectDetails/ClientMediaTabs";
import ClientMusicDetailsTab from "Components/Client/ClientViewProjectDetails/ClientMusicDetailsTab";
import ProcessedPayment from "Components/ProcessedPayment";
import ClientSurveyTab from "Components/Client/ClientViewProjectDetails/ClientSurveyTab";
import { getProjectDetailsClientAPI } from "Src/services/clientProjectDetailsService";
import { getAllProducersAPI } from "Src/services/clientService";
import { useSearchParams } from "react-router-dom";

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

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

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

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

  const [surveySubmitStatus, setSurveySubmitStatus] = React.useState(false);

  const [viewModel, setViewModel] = React.useState({});
  const [surveyLink, setSurveyLink] = React.useState("");
  const [settings, setSettings] = React.useState([]);
  const [projectTotal, setProjectTotal] = React.useState(0);
  const [managementDiscount, setManagementDiscount] = React.useState(0);
  const [netTotal, setNetTotal] = React.useState(0);
  const [isSubProject, setIsSubProject] = React.useState(true);
  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 [allProducers, setAllProducers] = 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 [deleteItemId, setDeleteItemId] = React.useState(null);
  const [showDeleteProjectModal, setShowDeleteProjectModal] =
    React.useState(false);

  const [subProjects, setSubProjects] = React.useState([]);
  const [ideas, setIdeas] = React.useState([]);
  const [selectedTeamNames, setSelectedTeamNames] = React.useState([]);
  const [selectedMixTypeIds, setSelectedMixTypeIds] = React.useState([]);
  const [selectedProducerNames, setSelectedProducerNames] = React.useState([]);
  const [mixDateStart, setMixDateStart] = React.useState("");
  const [mixDateEnd, setMixDateEnd] = 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 [expandAll, setExpandAll] = React.useState(false);

  const [isEdit, setIsEdit] = React.useState(false);
  const [selectedSubProjectIdsForDelete, setSelectedSubProjectIdsForDelete] =
    React.useState([]);

  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 [submittedIdeas, setSubmittedIdeas] = React.useState([]);

  const params = useParams();

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

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

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

  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 = removeKeysWhenValueIsNull({})) => {
    try {
      const result = await getProjectDetailsClientAPI(
        Number(params?.id),
        removeKeysWhenValueIsNull({
          ...filters,
          user_id: localStorage.getItem("user"),
        })
      );
      if (!result.error) {
        if (!result.model) {
          showToast(globalDispatch, "Access Denied", 5000, "error");
          navigate("/client/projects");
          return;
        }
        setViewModel(result.model);
        setProjectTotal(result.model?.total);
        setProgramName(result.model.program_name);
        setTeamName(result.model.team_name);
        setThemeOfTheRoutine(result.model?.theme_of_the_routine);
      } 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 result = await getSubProjectsByProjectIdAPI(Number(params?.id));
      if (!result.error) {
        // sort subProjects by type_name
        // type_name = 'Voiceover 3', 'Song 2', 'Voiceover 1', 'Voiceover 4', 'Song 1'
        // i want to sort it like this
        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);
        } else {
          setSubProjects([]);
          setVoiceCount(0);
          setSongCount(0);
          setTrackingCount(0);
          setTempVoiceCount(0);
          setTempSongCount(0);
          setTempTrackingCount(0);
        }

        // setSubProjects(result.list);
        //
        // type_name = 'Voiceover 1', 'Voiceover 2', 'Voiceover 3', 'Voiceover 4', 'Voiceover 5'
        // type_name = 'Song 1', 'Song 2', 'Song 3', 'Song 4', 'Song 5'
      } else {
        showToast(globalDispatch, result.message, 5000, "error");
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  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 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);
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  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}`;
        // let body = `Hello ${programName}, Thank you for choosing ${userCompanyName} as your music production company for this season. In order for us to start production on your mix for ${teamName}, we need you to fill out this survey. Please <a href="${surveyLink}">click here</a> to complete your survey. Thank you, ${userCompanyName}.`;
        // let payload = {
        //   from: 'myeq@equalityrecords.com',
        //   to: viewModel?.program_owner_email,
        //   subject: `New Music Survey for ${programName} ${teamName} - ${userCompanyName}`,
        //   body: body,
        // };

        // send email to client of survey
        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 loadFiltersFromStorage = () => {
    try {
      const userClientId = localStorage.getItem("userClientId");
      const producerName =
        localStorage.getItem("ClientProjectProducerName") &&
        JSON.parse(localStorage.getItem("ClientProjectProducerName"));
      const teamNames =
        localStorage.getItem("ClientProjectTeamName") &&
        JSON.parse(localStorage.getItem("ClientProjectTeamName"));
      const mixTypeIds =
        localStorage.getItem("ClientProjectMixTypeId") &&
        JSON.parse(localStorage.getItem("ClientProjectMixTypeId"));
      const startDate = localStorage.getItem("ClientProjectMixDateStart");
      const endDate = localStorage.getItem("ClientProjectMixDateEnd");

      setSelectedTeamNames(teamNames || []);
      setSelectedMixTypeIds(mixTypeIds || []);
      setSelectedProducerNames(producerName || []);
      setMixDateStart(startDate || "");
      setMixDateEnd(endDate || "");

      // Transform data for API
      let team_names = [];
      if (teamNames?.length > 0) {
        teamNames.forEach((row) => {
          team_names.push(row.value);
        });
      }
      let producer_names = [];
      if (producerName?.length > 0) {
        producerName.forEach((row) => {
          producer_names.push(row.value);
        });
      }

      let mix_type_ids = [];
      if (mixTypeIds?.length > 0) {
        mixTypeIds.forEach((row) => {
          mix_type_ids.push(row.value);
        });
      }

      // Validate dates
      if (startDate && endDate && startDate > endDate) {
        showToast(
          globalDispatch,
          "Mix Date Start must be less than Mix Date End",
          5000,
          "error"
        );
        return null;
      }
      return {
        producer_name: producer_names?.length > 0 ? producer_names : null,
        client_ids: userClientId ? [Number(userClientId)] : null,
        team_names: team_names?.length > 0 ? team_names : null,
        mix_type_ids: mix_type_ids?.length > 0 ? mix_type_ids : null,
        is_impersonate: false,
        mix_date_start: startDate
          ? moment(startDate).format("YYYY-MM-DD")
          : null,
        mix_date_end: endDate ? moment(endDate).format("YYYY-MM-DD") : null,
      };
    } catch (error) {
      console.error("Error loading filters:", error);
      return {};
    }
  };

  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;
      <div>ClientMusicDetailsTab</div>;
    }

    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 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 = (e) => {
    e.preventDefault();
    setIsSubProject(true);
    setIsIdea(false);
  };

  const handleIdeaClick = (e) => {
    e.preventDefault();
    setIsSubProject(false);
    setIsIdea(true);
  };

  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();
        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 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();
        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) {
          let linksArr = result.list.map((row) => row.url);

          const zipFileName = `Project_${programName}_${teamName}_master_files_${moment().format(
            "HH:mm:ss_DD-MM-YYYY"
          )}`;

          await downloadAsZipFilesByWebLinks(linksArr, zipFileName);
        } else {
          showToast(globalDispatch, "No master files found", 5000, "error");
          return;
        }
      }
    } 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();
        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(function () {
    globalDispatch({
      type: "SETPATH",
      payload: {
        path: "projects",
      },
    });

    const userId = localStorage.getItem("user");

    if (userId) {
      (async function () {
        await getUserDetails(userId);
      })();
    }

    (async function () {
      try {
        setIsLoading(true);
        // await retrieveAllSettings();
        await getProjectDetails(loadFiltersFromStorage());
        await getSubProjectsByProjectId();
        await getAllIdeasByProjectId();
        await getAllEmployeeByGroup();
        await getOneEmailBySlug();
        const res = await getAllProducersAPI();
        setAllProducers(res?.list || []);

        // await getAllProjectFiles();
        await getSurveyByProjectId(Number(params?.id));
        setIsLoading(false);
      } catch (error) {
        tokenExpireError(dispatch, error.message);
      }

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

      // return () => clearInterval(interval);

      const result = await getSurveyByProjectIdAPI(Number(params?.id));

      if (!result.error) {
        const url = new URL(BASE_URL + "survey/" + result.model.uuidv4);
        const uuidv4 = url.pathname.split("/survey/")[1];

        if (!uuidv4) {
          showToast(globalDispatch, "Invalid URL", 5000, "error");
        } else {
          const checkUuidv4 = validateUuidv4(uuidv4);
          if (!checkUuidv4) {
            showToast(globalDispatch, "Invalid URL", 5000, "error");
          } else {
            (async function () {
              const result = await getSurveyDetails({
                uuidv4,
              });
              if (!result.error) {
                if (result.model.status === 0) {
                  setSubmittedIdeas([]);
                } else if (result.model.status === 1) {
                  setSubmittedIdeas(result.model.ideas);
                }
              } else {
              }
            })();
          }
        }
      }
    })();
  }, []);

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

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

  const ClientSelectedTab = localStorage.getItem("ClientSelectedTab");
  const [selectedIndex, setSelectedIndex] = React.useState(
    ClientSelectedTab ? parseInt(ClientSelectedTab) : 0
  );

  React.useEffect(() => {
    localStorage.setItem("ClientSelectedTab", selectedIndex);
  }, [selectedIndex]);

  const orientationChangeHandler = (e) => {
    const portrait = e.matches;

    if (portrait && window.innerWidth <= 600) {
      showToast(
        globalDispatch,
        "Please rotate your device to landscape orientation for the best experience.",
        40000,
        "warning"
      );
    }
  };

  window
    .matchMedia("(orientation: portrait)")
    .addEventListener("change", orientationChangeHandler);

  const producerName = allProducers.find(
    (elem) => elem.user_id == viewModel?.user_id
  );

  const [searchParams] = useSearchParams();
  const pro = searchParams.get("pro");

  const queryParams = new URLSearchParams({
    params: params.id,
  }).toString();

  console.log(queryParams);

  return (
    <div className="max-w-screen w-full bg-boxdark-2 p-5">
      <div className="mx-auto rounded border border-strokedark bg-boxdark p-6">
        {viewModel && (
          <div>
            {/* Back Button 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>

            {/* 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>

              {/* Edit Request Button */}
              {(viewModel?.payment_status === 4 ||
                viewModel?.payment_status === 1) && (
                <button
                  onClick={() => navigate(`/client/edits?${queryParams}`)}
                  className="inline-flex items-center gap-2 rounded-md bg-primary px-4 py-2 text-sm font-medium text-white hover:bg-opacity-90"
                >
                  <FontAwesomeIcon icon="fas fa-edit" />
                  Request an Edit
                </button>
              )}
            </div>

            {/* Grid Layout for Info Cards */}
            <div className="mb-6 grid grid-cols-1 gap-4 md:grid-cols-2 xl:grid-cols-3">
              {/* 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>

              {/* Project Status 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">Producer:</span>
                    <span className="text-sm font-medium text-white">
                      {viewModel?.producer_name}
                    </span>
                  </div>
                  <div className="flex items-center justify-between">
                    <span className="text-sm text-bodydark2">Mix Season:</span>
                    <span className="text-sm font-medium text-white">
                      {viewModel?.mix_season_name}
                    </span>
                  </div>
                  <div className="flex items-center justify-between">
                    <span className="text-sm text-bodydark2">
                      Payment Status:
                    </span>
                    <span className="text-sm font-medium text-white">
                      {viewModel?.payment_status === 1 && "Complete"}
                      {viewModel?.payment_status === 2 && "Deposit Paid"}
                      {viewModel?.payment_status === 3 && "Paid in Full"}
                      {viewModel?.payment_status === 4 && "Awaiting Edit"}
                      {(viewModel?.payment_status === 5 ||
                        !viewModel?.payment_status) &&
                        "Unpaid"}
                    </span>
                  </div>
                </div>
              </div>

              {/* Dates 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">
                      Team Details Date:
                    </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>

            {/* Tabs Section */}
            <section className="mt-10">
              <Tab.Group
                selectedIndex={selectedIndex}
                onChange={setSelectedIndex}
              >
                <Tab.List className="mb-0 flex items-end gap-2 border-b border-strokedark md:items-center">
                  {["Team Details", "Survey", "8-Count", "Media"].map(
                    (tab, idx) => (
                      <Tab
                        key={tab}
                        className={`p-1 text-[0.8rem] font-bold text-bodydark2 hover:text-white sm:p-3 sm:text-sm md:text-base ${
                          selectedIndex === idx &&
                          "focus:ring-00 border-b-2 border-primary text-white focus-visible:outline-none"
                        }`}
                      >
                        {tab}
                      </Tab>
                    )
                  )}
                </Tab.List>

                <Tab.Panels className="focus:ring-00 w-full rounded-md border border-form-strokedark bg-form-input p-5 shadow focus-visible:outline-none">
                  <Tab.Panel>
                    <ClientMusicDetailsTab
                      viewModel={viewModel}
                      Team_Date={viewModel?.team_details_date}
                    />
                  </Tab.Panel>
                  <Tab.Panel>
                    <ClientSurveyTab
                      survey_id={viewModel?.survey_id}
                      surveyLink={surveyLink}
                      setShowResendSurveyModal={setShowResendSurveyModal}
                    />
                  </Tab.Panel>
                  <Tab.Panel>
                    <ClientEightCountTab
                      submittedIdeas={submittedIdeas}
                      viewModel={viewModel}
                      surveyLink={surveyLink}
                    />
                  </Tab.Panel>
                  <Tab.Panel>
                    <ClientMediaTabs viewModel={viewModel} />
                  </Tab.Panel>
                </Tab.Panels>
              </Tab.Group>
            </section>
          </div>
        )}
      </div>
    </div>
  );
};

export default ClientViewProjectPage;
