import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { yupResolver } from "@hookform/resolvers/yup";
import AddNoteModal from "Components/Modal/AddNoteModal";
import ConfirmModal from "Components/Modal/ConfirmModal";
import DuoConfirmModal from "Components/Modal/DuoConfirmModal";
import ViewNoteModal from "Components/Modal/ViewNoteModal";
import WorkOrderArtist from "Components/WorkOrder/Artist/WorkOrderArtist";
import WorkOrderArtistEngineer from "Components/WorkOrder/ArtistEngineer/WorkOrderArtistEngineer";
import WorkOrderEngineer from "Components/WorkOrder/Engineer/WorkOrderEngineer";
import WorkOrderWriter from "Components/WorkOrder/Writer/WorkOrderWriter";
import WorkOrderWriterArtist from "Components/WorkOrder/WriterArtist/WorkOrderWriterArtist";
import WorkOrderWriterArtistEngineer from "Components/WorkOrder/WriterArtistEngineer/WorkOrderWriterArtistEngineer";
import { AuthContext, tokenExpireError } from "Src/authContext";
import { GlobalContext, showToast } from "Src/globalContext";
import moment from "moment";
import React, { useEffect } from "react";
import { useForm } from "react-hook-form";
import { useNavigate, useParams } from "react-router-dom";
import * as yup from "yup";
// import CommonSwitch from 'Components/CommonSwitch';
import ModifyArtistModal from "Components/EditWorkOrder/ModifyArtistModal";
import ModifyEngineerModal from "Components/EditWorkOrder/ModifyEngineerModal";
import ModifyWriterModal from "Components/EditWorkOrder/ModifyWriterModal";
import EmptySessions from "Components/PublicWorkOrder/ArtistWorkOrder/EmptySessions";
import UploadedSessions from "Components/PublicWorkOrder/ArtistWorkOrder/UploadedSessions";
import EmptyLoops from "Components/PublicWorkOrder/WriterWorkOrder/EmptyLoops";
import UploadedLoops from "Components/PublicWorkOrder/WriterWorkOrder/UploadedLoops";
import WorkOrderCompleted from "Components/WorkOrder/Completed/WorkOrderCompleted";
import WriterNotesModal from "Components/WriterNotesModal";
import WorkOrderSubmission from "Components/workorderSubmission";
import { useS3Upload } from "Src/libs/uploads3Hook";
import { useS3UploadMaster } from "Src/libs/uploads3HookMaster";
import { sendEmailAPIV3 } from "Src/services/emailService";
import { getAllEmployeeByGroupAPI } from "Src/services/employeeService";
import {
  deleteOneFileAPI,
  updateSubProjectDetailsAPI,
} from "Src/services/projectService";
import { retrieveAllSettingsAPI } from "Src/services/settingService";
import {
  addNoteAPI,
  deleteS3FileAPI,
  deleteWorkOrderAPI,
  getWorkOrderDetailsAPI,
  updateLyricsPublicAPI,
  updateStatusAPI,
  updateWorkOrderAPI,
  updateWorkOrderArtistAPI,
  updateWorkOrderEngineerAPI,
  updateWorkOrderWriterAPI,
  uploadFilesDataAPI,
} from "Src/services/workOrderService";
import {
  dateTimeToFormattedString,
  resetSubProjectsChronology,
  sortByStringAsc,
  uuidv4,
} from "Utils/utils";
import { ClipLoader } from "react-spinners";

const columns = [
  {
    header: "Date",
    accessor: "create_at",
    isSorted: false,
    isSortedDesc: false,
    mappingExist: false,
    mappings: {},
  },
  {
    header: "Id",
    accessor: "workorder_code",
    isSorted: false,
    isSortedDesc: false,
    mappingExist: false,
    mappings: {},
  },
  {
    header: "Writer",
    accessor: "writer_id",
    isSorted: false,
    isSortedDesc: false,
    mappingExist: false,
    mappings: {},
  },
  {
    header: "Artist",
    accessor: "artist_id",
    isSorted: false,
    isSortedDesc: false,
    mappingExist: false,
    mappings: {},
  },
  {
    header: "Engineer",
    accessor: "engineer_id",
    isSorted: false,
    isSortedDesc: false,
    mappingExist: false,
    mappings: {},
  },
  {
    header: "Status",
    accessor: "status",
    isSorted: false,
    isSortedDesc: true,
    mappingExist: true,
    mappings: {
      1: "Writer",
      2: "Artist",
      3: "Engineer",
      4: "Rejected",
      5: "Completed",
      6: "Inactive",
    },
  },
];

const EditWorkOrderPage = () => {
  const { dispatch, state: authState } = React.useContext(AuthContext);
  const { dispatch: globalDispatch, state } = React.useContext(GlobalContext);
  const [uploadedSessions, setUploadedSessions] = React.useState([]);

  const {
    subProjectLyricsEditWorkOrder,
    songSubProjectsEditWorkOrder,
    subproject_update,
  } = state;

  const schema = yup
    .object({
      writer_id: yup.string(),
      artist_id: yup.string(),
      engineer_id: yup.string(),
    })
    .required();

  const navigate = useNavigate();

  const [isLoading, setIsLoading] = React.useState(true);
  const [showNoteModal, setShowNoteModal] = React.useState(false);
  const [showDeleteWorkOrderModal, setShowDeleteWorkOrderModal] =
    React.useState(false);
  const [showRealDeleteWorkOrderModal, setShowRealDeleteWorkOrderModal] =
    React.useState(false);
  const [showViewNoteModal, setShowViewNoteModal] = React.useState(false);
  const [note, setNote] = React.useState("");
  const [writerCost, setWriterCost] = React.useState(0);
  const [artistCost, setArtistCost] = React.useState(0);
  const [engineerCost, setEngineerCost] = React.useState(0);
  const [totalCost, setTotalCost] = React.useState(0);
  const [tableData, setTableData] = React.useState([]);
  const [subProjects, setSubProjects] = React.useState([]);
  const [workOrderDetails, setWorkOrderDetails] = React.useState({});
  const [sessions, setSessions] = React.useState([]);
  const [status, setStatus] = React.useState(0); // 11->Writer/Artist, 12->Writer/Artist/Engineer
  const [artistAndEngineer, setArtistAndEngineer] = React.useState(false);
  const [managementValue, setManagementValue] = React.useState(null);
  const [managementValueType, setManagementValueType] = React.useState(null);
  const [artistDeadline, setArtistDeadline] = React.useState(null);
  const [engineerDeadline, setEngineerDeadline] = React.useState(null);
  const [artistEngineerDeadline, setArtistEngineerDeadline] =
    React.useState(null);
  const [canUpload, setCanUpload] = React.useState(false);
  const [canUpload2, setCanUpload2] = React.useState(false);

  const [uploadedLoops, setUploadedLoops] = React.useState([]);
  const [employeeType, setEmployeeType] = React.useState("");
  const [fileType, setFileType] = React.useState("");
  const [employeeId, setEmployeeId] = React.useState(null);
  const { uploadS3FilesAPI, progress, error, isUploading } = useS3Upload();

  console.log(subProjects);

  const {
    uploadS3FilesAPI: uploadLoopsAPI,
    progress: progressLoops,
    error: errorLoops,
    isUploading: isUploadingLoops,
  } = useS3UploadMaster();

  const [voiceoverEightCount, setVoiceoverEightCount] = React.useState(null);
  const [songEightCount, setSongEightCount] = React.useState(null);
  const [trackingEightCount, setTrackingEightCount] = React.useState(null);
  const [writers, setWriters] = React.useState([]);
  const [artists, setArtists] = React.useState([]);
  const [engineers, setEngineers] = React.useState([]);
  const [selectedWriterId, setSelectedWriterId] = React.useState(null);
  const [selectedArtistId, setSelectedArtistId] = React.useState(null);
  const [selectedEngineerId, setSelectedEngineerId] = React.useState(null);
  const [showModifyWriterModal, setShowModifyWriterModal] =
    React.useState(false);
  const [showModifyArtistModal, setShowModifyArtistModal] =
    React.useState(false);
  const [showModifyEngineerModal, setShowModifyEngineerModal] =
    React.useState(false);
  const [showWriterNotesModal, setShowWriterNotesModal] = React.useState(false);
  const [
    showWorkOrderSubmissionDatesModal,
    setShowWorkOrderSubmissionDatesModal,
  ] = React.useState(false);

  const [submissionData, setSubmissionData] = React.useState([]);

  console.log(subProjects, status);

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

  const params = useParams();

  const retrieveAllSettings = async () => {
    try {
      const result = await retrieveAllSettingsAPI();
      if (!result.error) {
        // set all settings that matches with SETTING_KEYS
        if (result.list.length > 0) {
          result.list.forEach((row) => {
            if (row.setting_key === "management_value") {
              setManagementValue(row.setting_value);
            }
            if (row.setting_key === "management_value_type") {
              setManagementValueType(row.setting_value);
            }
            if (row.setting_key === "artist_deadline") {
              setArtistDeadline(row.setting_value);
            }
            if (row.setting_key === "engineer_deadline") {
              setEngineerDeadline(row.setting_value);
            }
            if (row.setting_key === "artist_engineer_deadline") {
              setArtistEngineerDeadline(row.setting_value);
            }
            if (row.setting_key === "voiceover_eight_count") {
              setVoiceoverEightCount(row.setting_value);
            }
            if (row.setting_key === "song_eight_count") {
              setSongEightCount(row.setting_value);
            }
            if (row.setting_key === "tracking_eight_count") {
              setTrackingEightCount(row.setting_value);
            }
          });
        }
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };
  useEffect(() => {
    (async function () {
      await getWorkOrderDetails(Number(params?.id));
    })();
  }, [subproject_update]);

  console.log(status, "hiii");

  const getWorkOrderDetails = async (id) => {
    try {
      setIsLoading(true);
      const result = await getWorkOrderDetailsAPI(id);
      if (!result.error) {
        setTableData([result.model]);
        setNote(result.model.note ? result.model.note : "");

        checkSubmissions(result.model);

        let writerTotalCost = result.model.writerTotalCost ?? 0;
        let artistTotalCost = result.model.artistTotalCost ?? 0;
        let engineerTotalCost = result.model.engineerTotalCost;

        let totalCost = writerTotalCost + artistTotalCost + engineerTotalCost;

        setWriterCost(writerTotalCost);
        setArtistCost(artistTotalCost);
        setEngineerCost(engineerTotalCost);
        setTotalCost(totalCost);
        // setSubProjects(result.model.sub_projects);
        setSessions(result.model.sessions);
        setWorkOrderDetails(result.model);
        setStatus(result.model.status);
        setUploadedLoops(result.model.instrumentals);
        setUploadedSessions(result.model.sessions);

        console.log(
          Number(result.model.artist.id),
          Number(result.model.engineer.id)
        );

        if (!result.model.writer_submit_status) {
          setCanUpload(true);
        }
        if (!result.model.artist_submit_status) {
          setCanUpload2(true);
        }
        if (result.model.auto_approve === 1) {
          if (
            result.model.writer_id === result.model.artist_id &&
            result.model.writer_id !== result.model.engineer_id
          ) {
            if (result.model.status === 5) {
              // completed
              setStatus(result.model.status);
            } else if (result.model.status === 3) {
              // engineer
              setStatus(3);
            } else {
              // writer/artist
              setStatus(11);
            }
          }
          if (
            result.model.writer_id === result.model.artist_id &&
            result.model.writer_id === result.model.engineer_id &&
            result.model.status === 1
          ) {
            console.log("hii");
            if (result.model.status === 5) {
              // completed
              setStatus(result.model.status);
            } else {
              // writer/artist/engineer
              setStatus(12);
            }
          }
        }

        setSelectedWriterId(result.model.writer.id);
        setSelectedArtistId(result.model.artist.id);
        setSelectedEngineerId(result.model.engineer.id);

        if (
          Number(result.model.artist.id) === Number(result.model.engineer.id)
        ) {
          //
          setArtistAndEngineer(true);
        }

        setSubProjects(resetSubProjectsChronology(result.model.sub_projects));
        setIsLoading(false);
      }
    } catch (error) {
      setIsLoading(false);
      tokenExpireError(dispatch, error.message);
    }
  };

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

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

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

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

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

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

  const handleSaveAll = async () => {
    try {
      if (
        songSubProjectsEditWorkOrder.length === 0 &&
        subProjectLyricsEditWorkOrder.length === 0
      ) {
        showToast(
          globalDispatch,
          "No changes found to update the all sub project details",
          5000,
          "warning"
        );
        setIsLoading(false);
        return;
      }
      await handleSaveAllLyrics();
      await handleSaveAllSubProjectDetails();
      globalDispatch({
        type: "SET_SUBPROJECT_UPDATE",
        payload: !subproject_update,
      });
      // window.location.reload();
    } catch (error) {
      showToast(globalDispatch, error.message, 5000, "error");
    }
  };

  const handleSaveAllLyrics = async () => {
    try {
      // subProjectLyrics
      // [{
      //    subproject_id: subProjectId,
      //    lyrics: e.target.value,
      // }]

      console.log(subProjectLyricsEditWorkOrder);

      const updateLyricsPromises = subProjectLyricsEditWorkOrder.map((row) => {
        return updateLyricsPublicAPI({
          subproject_id: row.subproject_id,
          lyrics: row.lyrics,
        });
      });

      const results = await Promise.all(updateLyricsPromises);

      // Check if all updates were successful
      const allSuccessful = results.every((result) => !result.error);

      if (allSuccessful) {
        showToast(globalDispatch, "Lyrics updated successfully", 5000);
        // window.location.reload();
        globalDispatch({
          type: "SET_SUBPROJECT_UPDATE",
          payload: !subproject_update,
        });
      } else {
        showToast(globalDispatch, "Error updating lyrics", 5000, "error");
      }
      setIsLoading(false);
    } catch (error) {
      showToast(globalDispatch, error.message, 5000, "error");
    }
  };

  const handleSaveAllSubProjectDetails = async () => {
    try {
      // songSubProjects
      // [{
      //    subproject_id: 123,
      //    type_name: 'Hola Amigo',
      //    bpm: '125',
      //    song_key: 'C',
      //    is_song: 1,
      // }]

      const updateSubProjectDetailsPromises = songSubProjectsEditWorkOrder.map(
        (row) => {
          return updateSubProjectDetailsAPI({
            subproject_id: row.subproject_id,
            type_name: row.type_name,
            bpm: row.bpm,
            song_key: row.song_key,
            is_song: row.is_song,
          });
        }
      );

      const results = await Promise.all(updateSubProjectDetailsPromises);

      // Check if all updates were successful
      const allSuccessful = results.every((result) => !result.error);

      if (allSuccessful) {
        showToast(
          globalDispatch,
          "All Sub-project details updated successfully",
          5000
        );
        globalDispatch({
          type: "SET_SUBPROJECT_UPDATE",
          payload: !subproject_update,
        });
        // window.location.reload();
      } else {
        showToast(
          globalDispatch,
          "Error updating all sub-project details",
          5000,
          "error"
        );
        globalDispatch({
          type: "SET_SUBPROJECT_UPDATE",
          payload: !subproject_update,
        });
      }
      setIsLoading(false);
    } catch (error) {
      showToast(globalDispatch, error.message, 5000, "error");
    }
  };

  const handleUpdateLyrics = async (payload) => {
    try {
      const result = await updateLyricsPublicAPI(payload);
      if (!result.error) {
        showToast(globalDispatch, "Lyrics updated successfully", 5000);
        globalDispatch({
          type: "SET_SUBPROJECT_UPDATE",
          payload: !subproject_update,
        });
        setIsLoading(false);
      } else {
        showToast(globalDispatch, result.message, 5000, "error");
        setIsLoading(false);
      }
    } catch (error) {
      showToast(globalDispatch, error.message, 5000, "error");
    }
  };

  const handleViewNoteModalClose = () => {
    setShowViewNoteModal(false);
  };

  const handleNoteModalClose = () => {
    setShowNoteModal(false);
  };

  const handleModifyWriterModalClose = () => {
    setShowModifyWriterModal(false);
  };

  const handleModifyArtistModalClose = () => {
    setShowModifyArtistModal(false);
  };

  const handleModifyEngineerModalClose = () => {
    setShowModifyEngineerModal(false);
  };

  const handleSubmitNote = async (note) => {
    try {
      setIsLoading(true);
      const result = await addNoteAPI({
        id: Number(params?.id),
        note,
      });

      if (!result.error) {
        showToast(globalDispatch, result.message, 4000);
        setShowNoteModal(false);
        await getWorkOrderDetails(Number(params?.id));
        setIsLoading(false);
      } else {
        showToast(globalDispatch, result.message, 4000);
        setIsLoading(false);
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  const handleDeleteWorkOrderModalClose = () => {
    setShowDeleteWorkOrderModal(false);
  };

  const handleRealDeleteWorkOrderModalClose = () => {
    setShowRealDeleteWorkOrderModal(false);
  };

  const handleDeleteWorkOrder = async () => {
    try {
      setIsLoading(true);
      const result = await updateStatusAPI({
        id: Number(params?.id),
        status: 2,
      });

      if (!result.error) {
        showToast(globalDispatch, result.message, 4000);
        setShowDeleteWorkOrderModal(false);
        await getWorkOrderDetails(Number(params?.id));
        setIsLoading(false);
      } else {
        showToast(globalDispatch, result.message, 4000);
        setIsLoading(false);
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  const handleApproveWorkOrder = async () => {
    try {
      // setIsLoading(true);
      // let existingDueDate = moment(workOrderDetails.due_date).format(
      //   'YYYY-MM-DD'
      // );
      // let artistDueDate = moment(existingDueDate).add(
      //   Number(artistDeadline),
      //   'days'
      // );
      // artistDueDate = moment(artistDueDate).format('YYYY-MM-DD');

      let currentDay = moment().format("MM/DD/YYYY");
      let dueDate = moment(currentDay).add(Number(artistDeadline), "days");

      if (Number(selectedArtistId) === Number(selectedEngineerId)) {
        // artist and engineer are same
        dueDate = moment(currentDay).add(
          Number(artistEngineerDeadline),
          "days"
        );
      }

      dueDate = moment(dueDate).format("YYYY-MM-DD");

      const result = await updateWorkOrderAPI({
        id: Number(params?.id),
        writer_submit_status: 1,
        due_date: dueDate,
        engineer_deadline: Number(engineerDeadline),
        status: 2,
      });

      if (!result.error) {
        let subProjects = workOrderDetails.sub_projects;
        let voiceOverCount = 0;
        let songCount = 0;
        let totalEightCount = 0;

        subProjects.forEach((subProject) => {
          if (subProject.type.includes("Voiceover")) {
            voiceOverCount++;
          }
          if (subProject.is_song === 1) {
            songCount++;
          }
          totalEightCount += subProject.eight_count;
        });

        // employee_name,link,voiceover_count,eight_count,contents
        const artistWorkOrderLink = `https://equalityrecords.com/work-order/artist/${workOrderDetails.uuidv4}`;
        const artistEngineerWorkOrderLink = `https://equalityrecords.com/work-order/engineer-artist/${workOrderDetails.uuidv4}`;

        const artistEmailSubject = `Artist Work Order ${workOrderDetails.workorder_code} has been placed by ${workOrderDetails.user.company_name}`;
        const artistEngineerEmailSubject = `Artist/Engineer Work Order ${workOrderDetails.workorder_code} has been placed by ${workOrderDetails.user.company_name}`;

        const artistBody = `Due Date: ${dateTimeToFormattedString(dueDate)}
          <br><br>An order for you to record has been placed. Below are the lyrics and demos for each team. Please upload your session files using this link: ${artistWorkOrderLink}.
          <br><br>Number of Voiceovers: ${voiceOverCount}.
          <br>Number of Songs: ${songCount}.
          <br><br>Total Number of 8-counts: ${totalEightCount}.`;

        const artistEngineerBody = `Due Date:  ${dateTimeToFormattedString(
          dueDate
        )}
          <br><br>An order for you to record has been placed. Below are the lyrics and demos for each team. Please upload your session and master files using this link: ${artistEngineerWorkOrderLink}.
          <br><br>Number of Voiceovers: ${voiceOverCount}.
          <br><br>Number of Songs: ${songCount}.
          <br><br>Total Number of 8-counts: ${totalEightCount}.<br>`;

        const payload = {
          from: "myeq@equalityrecords.com",
          to: workOrderDetails.artist.email,
          subject: artistAndEngineer
            ? artistEngineerEmailSubject
            : artistEmailSubject,
          body: artistAndEngineer ? artistEngineerBody : artistBody,
        };

        const emailResult = await sendEmailAPIV3(payload);

        if (!emailResult.error) {
          showToast(
            globalDispatch,
            "Approved and " + emailResult.message,
            5000
          );
          window.location.reload();
        } else {
          showToast(globalDispatch, emailResult.message, 5000, "error");
          return;
        }
      } else {
        showToast(globalDispatch, result.message, 4000, "error");
        return;
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  const handleCompleteWorkOrder = async () => {
    try {
      setIsLoading(true);
      const result = await updateWorkOrderAPI({
        id: Number(params?.id),
        writer_submit_status: 1,
        artist_submit_status: 1,
        engineer_submit_status: 1,
        status: 5,
        is_viewed: 0,
      });

      if (!result.error) {
        showToast(globalDispatch, result.message, 4000);
        // await getWorkOrderDetails(Number(params?.id));
        setIsLoading(false);
        window.location.reload();
      } else {
        showToast(globalDispatch, result.message, 4000);
        setIsLoading(false);
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  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);
            console.log(subproject_update);
            globalDispatch({
              type: "SET_SUBPROJECT_UPDATE",
              payload: !subproject_update,
            });
          }
        }
      } else {
        showToast(globalDispatch, result.message, 5000, "error");
      }
    } catch (error) {
      showToast(globalDispatch, error.message, 5000, "error");
    }
  };

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

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

  const handleRealDeleteWorkOrder = async () => {
    try {
      setIsLoading(true);
      const result = await deleteWorkOrderAPI(params?.id);
      if (!result.error) {
        showToast(globalDispatch, result.message, 4000);
        setIsLoading(false);
        window.location.href = `/${authState.role}/work-orders`;
      } else {
        showToast(globalDispatch, result.message, 4000);
        setIsLoading(false);
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  const handleModifySubProjectWriter = async (data) => {
    try {
      const payload = {
        writer_id: Number(data.writer_id),
        writer_cost: data.writer_cost,
        workorder_id: Number(params?.id),
      };
      const result = await updateWorkOrderWriterAPI(payload);

      console.log(result, "resultwriter");
      //

      let urlPart3 = "writer";
      let startPartOfSubject = "Writing";
      if (
        Number(data.writer_id) === workOrderDetails.artist_id &&
        Number(data.writer_id) !== workOrderDetails.engineer_id &&
        workOrderDetails.auto_approve === 1
      ) {
        urlPart3 = "writer-artist";
        startPartOfSubject = "Writing Artist";
      } else if (
        Number(data.writer_id) === workOrderDetails.artist_id &&
        Number(data.writer_id) === workOrderDetails.engineer_id &&
        workOrderDetails.auto_approve === 1
      ) {
        urlPart3 = "writer-artist-engineer";
        startPartOfSubject = "Writing Artist Engineer";
      } else if (
        Number(data.writer_id) !== workOrderDetails.artist_id &&
        workOrderDetails.auto_approve === 1
      ) {
        urlPart3 = "writer";
        startPartOfSubject = "Writing";
      }

      let localUuidV4 = uuidv4();

      if (!result.error) {
        // showToast(globalDispatch, result.message, 5000);
        setShowModifyWriterModal(false);

        if (status === 1) {
          // status = writer
          // send email to the new writer only

          await updateWorkOrderAPI({
            id: Number(params?.id),
            uuidv4: localUuidV4,
            writer_submit_status: 0,
            // status: 1,
          });
          await handleTriggerEmailToWriter(
            result,
            localUuidV4,
            urlPart3,
            startPartOfSubject
          );
        } else {
          if (
            Number(data.writer_id) !== workOrderDetails.artist_id &&
            workOrderDetails.auto_approve === 1
          ) {
            await updateWorkOrderAPI({
              id: Number(params?.id),
              uuidv4: localUuidV4,
              writer_submit_status: 0,
              // status: 1,
            });
            await handleTriggerEmailToWriter(
              result,
              localUuidV4,
              urlPart3,
              startPartOfSubject
            );
          } else if (
            Number(data.writer_id) !== workOrderDetails.artist_id &&
            Number(data.writer_id) !== workOrderDetails.engineer_id &&
            workOrderDetails.auto_approve === 1
          ) {
            await updateWorkOrderAPI({
              id: Number(params?.id),
              uuidv4: localUuidV4,
              writer_submit_status: 0,
              // status: 1,
            });
            await handleTriggerEmailToWriter(
              result,
              localUuidV4,
              urlPart3,
              startPartOfSubject
            );
          } else {
            await updateWorkOrderAPI({
              id: Number(params?.id),
              writer_submit_status: 0,
              // status: 1,
            });
            showToast(globalDispatch, result.message, 5000);
            window.location.reload();
          }
        }
      } else {
        showToast(globalDispatch, result.message, 5000, "error");
        setShowModifyWriterModal(false);
        return;
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  const handleModifySubProjectArtist = async (data) => {
    try {
      const payload = {
        artist_id: Number(data.artist_id),
        artist_cost: data.artist_cost,
        workorder_id: Number(params?.id),
      };
      const result = await updateWorkOrderArtistAPI(payload);
      console.log(result, "resultaritstsub");
      //

      let urlPart3 = "artist";
      let startPartOfSubject = "Artist";
      if (
        workOrderDetails.writer_id === Number(data.artist_id) &&
        workOrderDetails.auto_approve === 1
      ) {
        urlPart3 = "writer-artist";
        startPartOfSubject = "Writing Artist";
      } else if (
        workOrderDetails.writer_id === Number(data.artist_id) &&
        workOrderDetails.writer_id === workOrderDetails.engineer_id &&
        workOrderDetails.auto_approve === 1 &&
        workOrderDetails.status === 1
      ) {
        urlPart3 = "writer-artist-engineer";
        startPartOfSubject = "Writing Artist Engineer";
      } else if (Number(data.artist_id) === workOrderDetails.engineer_id) {
        urlPart3 = "engineer-artist";
        startPartOfSubject = "Artist/Engineer";
      }

      let localUuidV4 = uuidv4();

      if (!result.error) {
        // showToast(globalDispatch, result.message, 5000);
        setShowModifyArtistModal(false);

        if (status === 2) {
          // status = artist
          // send email to artist and engineer
          await updateWorkOrderAPI({
            id: Number(params?.id),
            uuidv4: localUuidV4,
            artist_submit_status: 0,
            // status: status,
          });

          await handleTriggerEmailToArtist(
            result,
            localUuidV4,
            urlPart3,
            startPartOfSubject
          );
        } else {
          if (
            workOrderDetails.writer_id === Number(data.artist_id) &&
            workOrderDetails.writer_id !== workOrderDetails.engineer_id &&
            workOrderDetails.auto_approve === 1
          ) {
            await updateWorkOrderAPI({
              id: Number(params?.id),
              uuidv4: localUuidV4,
              artist_submit_status: 0,
              // status: status,
            });
            await handleTriggerEmailToWriter(
              result,
              localUuidV4,
              urlPart3,
              "Writing Artist"
            );
          } else if (
            workOrderDetails.writer_id === Number(data.artist_id) &&
            workOrderDetails.writer_id === workOrderDetails.engineer_id &&
            workOrderDetails.auto_approve === 1
          ) {
            await updateWorkOrderAPI({
              id: Number(params?.id),
              uuidv4: localUuidV4,
              artist_submit_status: 0,
              // status: status,
            });
            await handleTriggerEmailToWriter(
              result,
              localUuidV4,
              urlPart3,
              "Writing Artist Engineer"
            );
          } else {
            await updateWorkOrderAPI({
              id: Number(params?.id),
              artist_submit_status: 0,
              // status: status,
            });
            showToast(globalDispatch, result.message, 5000);
            globalDispatch({
              type: "SET_SUBPROJECT_UPDATE",
              payload: !subproject_update,
            });
          }
        }
      } else {
        showToast(globalDispatch, result.message, 5000, "error");
        setShowModifyWriterModal(false);
        return;
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  const handleModifySubProjectEngineer = async (data) => {
    try {
      const payload = {
        engineer_id: Number(data.engineer_id),
        engineer_cost: data.engineer_cost,
        workorder_id: Number(params?.id),
      };
      const result = await updateWorkOrderEngineerAPI(payload);
      console.log(result, "resultengsub");
      //

      let urlPart3 = "engineer";
      if (
        workOrderDetails.writer_id === workOrderDetails.artist_id &&
        workOrderDetails.writer_id === Number(data.engineer_id) &&
        workOrderDetails.auto_approve === 1
      ) {
        urlPart3 = "writer-artist-engineer";
      } else if (
        workOrderDetails.artist_id ===
        Number(data.engineer_id && workOrderDetails.auto_approve !== 1)
      ) {
        urlPart3 = "engineer-artist";
      }

      let localUuidV4 = uuidv4();

      if (!result.error) {
        // showToast(globalDispatch, result.message, 5000);
        setShowModifyEngineerModal(false);

        if (status === 3) {
          // status = engineer
          // send email to engineer

          await updateWorkOrderAPI({
            id: Number(params?.id),
            uuidv4: localUuidV4,
            engineer_submit_status: 0,
            // status: status,
          });

          console.log(result, "engineeer");
          await handleTriggerEmailToEngineer(result, localUuidV4, urlPart3);
        } else {
          if (
            workOrderDetails.writer_id === workOrderDetails.artist_id &&
            workOrderDetails.writer_id === Number(data.engineer_id) &&
            workOrderDetails.auto_approve === 1
          ) {
            console.log("hi2");
            // urlPart3 = 'writer-artist-engineer';
            await updateWorkOrderAPI({
              id: Number(params?.id),
              uuidv4: localUuidV4,
              engineer_submit_status: 0,
              // status: status,
            });

            await handleTriggerEmailToWriter(
              result,
              localUuidV4,
              urlPart3,
              "Writing Artist Engineer"
            );
          } else if (
            workOrderDetails.artist_id ===
            Number(data.engineer_id && workOrderDetails.auto_approve !== 1)
          ) {
            // urlPart3 = 'engineer-artist';
            await updateWorkOrderAPI({
              id: Number(params?.id),
              uuidv4: localUuidV4,
              engineer_submit_status: 0,
              // status: status,
            });

            await handleTriggerEmailToArtist(
              result,
              localUuidV4,
              urlPart3,
              "Artist/Engineer"
            );
          } else {
            await updateWorkOrderAPI({
              id: Number(params?.id),
              engineer_submit_status: 0,
              // status: status,
            });
            showToast(globalDispatch, result.message, 5000);
            globalDispatch({
              type: "SET_SUBPROJECT_UPDATE",
              payload: !subproject_update,
            });
            // window.location.reload();
          }
        }
      } else {
        showToast(globalDispatch, result.message, 5000, "error");
        setShowModifyWriterModal(false);
        return;
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

  const handleWorkorderSubmitModalClose = () => {
    setShowWorkOrderSubmissionDatesModal(false);
  };
  const handleWriterNotesModalClose = () => {
    setShowWriterNotesModal(false);
  };

  const handleTriggerEmailToWriter = async (
    result,
    localUuidV4,
    urlPart3,
    startPartOfSubject
  ) => {
    if (result.model.sub_projects.length > 0) {
      result.model.sub_projects = resetSubProjectsChronology(
        result.model.sub_projects
      );
    }

    let emailSubject = `${startPartOfSubject} Work Order ${result.model.workorder_code}: ${result.model.writer_name} for ${result.model.artist_name} has been placed by ${result.model.user.company_name}`;
    const workOrderWriterLink = `https://equalityrecords.com/work-order/${urlPart3}/${localUuidV4}`;
    let htmlBody = `Due Date:  ${dateTimeToFormattedString(
      result?.model?.due_date
    )}
          <br><br>An order for your writing has been placed. Below are the notes for each team from the coach and the producer. Please upload your demos and lyrics using this link: ${workOrderWriterLink}.
          <br><br>Number of Voiceovers: ${result.model.voiceover_count}.
          <br>Number of Songs: ${result.model.song_count}.
          <br><br>Total Number of 8-counts: ${result.model.total_eight_count}.
          <br><br>
          ${
            result.model.sub_projects.length > 0
              ? result.model.sub_projects
                  .map((row) => {
                    console.log(row, "dhhdhhd");
                    return `<b><u>${row.type}: ${
                      row?.program_name
                        ? `${row.program_name} - ${row?.team_name}`
                        : "Unassigned"
                    }</u></b><br>
                    Number of 8-counts: ${row.eight_count || "N/A"}<br>
                   Team Type: ${
                     (Number(row.team_type) === 1 && "All Girl") ||
                     (Number(row.team_type) === 2 && "Co-ed") ||
                     (Number(row.team_type) === 3 && "TBD")
                   }<br>
                    Theme: ${
                      row.survey.theme_of_the_routine
                        ? row.survey.theme_of_the_routine
                        : "N/A"
                    }<br>
                    Division: ${row.division || "N/A"}<br>
                    Colors: ${row.colors || "N/A"}<br>
                   Notes: <br>${
                     row.ideas && row.ideas.length > 0
                       ? `<ul>${row.ideas
                           .map(
                             (idea) =>
                               `<li>${idea.idea_value
                                 .split("\n")
                                 .join("<br>")}</li>`
                           )
                           .join("")}</ul><br>`
                       : `${row.notes || "N/A"}<br><br>`
                   }<br><br>`;
                  })
                  .join("")
              : "N/A"
          }
          <br>
          `;
    let payload = {
      from: "myeq@equalityrecords.com",
      to: result.model.writer_email,
      subject: emailSubject,
      body: htmlBody,
    };
    const emailResult = await sendEmailAPIV3(payload);
    if (!emailResult.error) {
      setIsLoading(false);
      showToast(
        globalDispatch,
        "Writer updated & email sent to the new writer",
        5000
      );
      window.location.reload();
    } else {
      setIsLoading(false);
      showToast(globalDispatch, result.message, 5000, "error");
      return;
    }
  };

  const handleTriggerEmailToArtist = async (
    result,
    localUuidV4,
    urlPart3,
    startPartOfSubject
  ) => {
    console.log(result, "resultart");
    let emailSubject = `${startPartOfSubject} Work Order ${result.model.workorder_code}: ${result.model.writer_name} for ${result.model.artist_name} has been placed by ${result.model.user.company_name}`;
    const workOrderArtistLink = `https://equalityrecords.com/work-order/${urlPart3}/${localUuidV4}`;
    let htmlBody = `Due Date: ${dateTimeToFormattedString(
      result?.model?.due_date
    )}
          <br><br>An order for you to record has been placed. Below are the lyrics and demos for each team. Please upload your session files ${
            urlPart3 === "engineer-artist" ? "and master files" : ""
          } using this link: ${workOrderArtistLink}.
          <br><br>Number of Voiceovers: ${result.model.voiceover_count}.
          <br>Number of Songs: ${result.model.song_count}.
          <br><br>Total Number of 8-counts: ${result.model.total_eight_count}.
          <br><br>
          `;

    const payload = {
      from: "myeq@equalityrecords.com",
      to: result.model.artist_email,
      subject: emailSubject,
      body: htmlBody,
    };

    const emailResult = await sendEmailAPIV3(payload);
    if (!emailResult.error) {
      setIsLoading(false);
      showToast(
        globalDispatch,
        "Artist updated & email sent to the new artist",
        5000
      );
      window.location.reload();
    } else {
      setIsLoading(false);
      showToast(globalDispatch, result.message, 5000, "error");
      return;
    }
  };

  const handleTriggerEmailToEngineer = async (
    result,
    localUuidV4,
    urlPart3
  ) => {
    if (result.model.sub_projects.length > 0) {
      result.model.sub_projects = resetSubProjectsChronology(
        result.model.sub_projects
      );
    }

    let emailSubject = `Engineer Work Order ${result.model.workorder_code}: ${result.model.writer_name} for ${result.model.artist_name} has been placed by ${result.model.user.company_name}`;
    const workOrderEngineerLink = `https://equalityrecords.com/work-order/${urlPart3}/${localUuidV4}`;
    let htmlBody = `Due Date: ${dateTimeToFormattedString(
      result?.model?.due_date
    )}
        <br><br>An order for you to engineer has been placed. Files have been attached. Please upload master files using this link: ${workOrderEngineerLink}.
          <br><br>Number of Voiceovers: ${result.model.voiceover_count}.
          <br>Number of Songs: ${result.model.song_count}.
          <br><br>Total Number of 8-counts: ${result.model.total_eight_count}.
          <br><br>
           ${
             result.model.sub_projects.length > 0
               ? result.model.sub_projects
                   .map((row) => {
                     return `<b><u>${row.type}: ${
                       row?.program_name
                         ? `${row.program_name} - ${row?.team_name}`
                         : "Unassigned"
                     }</u></b><br>
                    Number of 8-counts: ${row.eight_count}<br>
                   Team Type: ${
                     (Number(row.team_type) === 1 && "All Girl") ||
                     (Number(row.team_type) === 2 && "Co-ed") ||
                     (Number(row.team_type) === 3 && "TBD")
                   }<br>
                    Theme: ${
                      row.survey.theme_of_the_routine
                        ? row.survey.theme_of_the_routine
                        : "N/A"
                    }<br>
                    Colors: ${row.colors}<br>
                   Notes: <br>${
                     row.ideas && row.ideas.length > 0
                       ? `<ul>${row.ideas
                           .map(
                             (idea) =>
                               `<li>${idea.idea_value
                                 .split("\n")
                                 .join("<br>")}</li>`
                           )
                           .join("")}</ul><br>`
                       : "N/A<br><br>"
                   }<br><br>`;
                   })
                   .join("")
               : "N/A"
           }
          <br>
          
          `;
    const payload = {
      from: "myeq@equalityrecords.com",
      to: result.model.engineer_email,
      subject: emailSubject,
      body: htmlBody,
    };
    const emailResult = await sendEmailAPIV3(payload);
    if (!emailResult.error) {
      setIsLoading(false);
      showToast(
        globalDispatch,
        "Engineer updated & email sent to the new engineer",
        5000
      );
      window.location.reload();
    } else {
      setIsLoading(false);
      showToast(globalDispatch, result.message, 5000, "error");
      return;
    }
  };

  const handleAutoApprove = async (value) => {
    try {
      //
      // return;
      setIsLoading(true);
      const result = await updateWorkOrderAPI({
        id: Number(params?.id),
        auto_approve: value.auto_approve,
      });

      if (!result.error) {
        showToast(globalDispatch, result.message, 4000);
      } else {
        showToast(globalDispatch, result.message, 4000, "error");
      }
      await getWorkOrderDetails(Number(params?.id));
      await retrieveAllSettings();
      await getAllEmployeeByGroup();
      setIsLoading(false);
    } catch (error) {
      setIsLoading(false);
      tokenExpireError(dispatch, error.message);
    }
  };

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

    (async function () {
      setIsLoading(true);
      await getWorkOrderDetails(Number(params?.id));
      await retrieveAllSettings();
      await getAllEmployeeByGroup();
      setIsLoading(false);
    })();
  }, []);

  function checkSubmissions(response) {
    const {
      due_date,
      writer_submission_datetime,
      artist_submission_datetime,
      engineer_submission_datetime,
      artist_engineer_submission_datetime,
      writer_artist_submission_datetime,
      writer_artist_engineer_submission_datetime,
    } = response;

    const submissions = [
      {
        date: artist_engineer_submission_datetime,
        employee: "artist/engineer",
      },
      { date: writer_submission_datetime, employee: "writer" },
      { date: artist_submission_datetime, employee: "artist" },
      { date: engineer_submission_datetime, employee: "engineer" },
      { date: writer_artist_submission_datetime, employee: "writer/artist" },
      {
        date: writer_artist_engineer_submission_datetime,
        employee: "writer/artist/engineer",
      },
    ];

    const validSubmissions = submissions.filter(
      (submission) => submission.date
    );

    const submissionObjects = validSubmissions.map((submission) => {
      // const submissionDate = submission.date.split('T')[0];
      const status =
        new Date(submission.date).getTime() < new Date(due_date).getTime()
          ? "Early"
          : "Late";
      return {
        date: submission.date,
        status: status,
        employee: submission.employee,
      };
    });

    setSubmissionData(submissionObjects);
  }

  const formatDate = (dateString) => {
    // Split the dateString into day, month, and year parts

    const [year, month, day] = dateString?.split("-");

    // Create a new Date object with the provided year, month (subtract 1 because months are zero-indexed), and day
    const date = new Date(`${year}-${month}-${day}`);

    // Check if the date is valid
    if (isNaN(date.getTime())) {
      return null; // Return null if the date is invalid
    }

    // Format month to have leading zero if necessary
    const formattedMonth = (date.getMonth() + 1).toString().padStart(2, "0");

    // Format day to have leading zero if necessary
    const formattedDay = date.getDate().toString().padStart(2, "0");

    // Get the year portion
    const formattedYear = date.getFullYear();

    const formattedDate = `${formattedDay}/${formattedMonth}/${formattedYear}`;

    return formattedDate;
  };

  const handleEmployeeType = (employeeType) => {
    //
    setEmployeeType(employeeType);
    if (employeeType === "writer") {
      setEmployeeId(Number(workOrderDetails.writer_id));
    } else if (employeeType === "artist") {
      setEmployeeId(Number(workOrderDetails.artist_id));
    } else if (employeeType === "engineer") {
      setEmployeeId(Number(workOrderDetails.engineer_id));
    }
  };

  const handleUploadFileType = (fileType) => {
    setFileType(fileType);
  };

  const handleLoopUploads = async (formData) => {
    try {
      const result = await uploadLoopsAPI(formData);

      if (!result.error) {
        const payload = {
          project_id: workOrderDetails.project_id
            ? Number(workOrderDetails.project_id)
            : null,
          subproject_id: workOrderDetails.subproject_id
            ? Number(workOrderDetails.subproject_id)
            : null,
          workorder_id: Number(workOrderDetails.id),
          employee_id: Number(workOrderDetails.writer_id),
          employee_type: "writer",
          type: "instrumental",
          attachments: result.attachments,
        };

        const fileUploadDataResult = await uploadFilesDataAPI(payload);
        if (!fileUploadDataResult.error) {
          showToast(globalDispatch, "Files updated successfully", 5000);
          globalDispatch({
            type: "SET_SUBPROJECT_UPDATE",
            payload: !subproject_update,
          });
        } else {
          showToast(
            globalDispatch,
            fileUploadDataResult.message,
            5000,
            "error"
          );
        }
        setIsLoading(false);
      } else {
        showToast(globalDispatch, result.message, 5000, "error");
        setIsLoading(false);
      }
    } catch (error) {
      showToast(globalDispatch, error.message, 5000, "error");
    }
  };

  const handleSessionUploads = async (formData) => {
    try {
      const result = await uploadS3FilesAPI(formData);
      if (!result.error) {
        const payload = {
          project_id: workOrderDetails.project_id
            ? Number(workOrderDetails.project_id)
            : null,
          subproject_id: workOrderDetails.subproject_id
            ? Number(workOrderDetails.subproject_id)
            : null,
          workorder_id: workOrderDetails.id
            ? Number(workOrderDetails.id)
            : null,
          employee_id: Number(workOrderDetails.artist_id),
          employee_type: "artist",
          type: "session",
          attachments: result.attachments,
        };

        const fileUploadDataResult = await uploadFilesDataAPI(payload);
        if (!fileUploadDataResult.error) {
          showToast(globalDispatch, "Files updated successfully", 5000);
          globalDispatch({
            type: "SET_SUBPROJECT_UPDATE",
            payload: !subproject_update,
          });
        } else {
          showToast(
            globalDispatch,
            fileUploadDataResult.message,
            5000,
            "error"
          );
        }
        setIsLoading(false);
      } else {
        showToast(globalDispatch, result.message, 5000, "error");
        setIsLoading(false);
      }
    } catch (error) {
      showToast(globalDispatch, error.message, 5000, "error");
    }
  };

  console.log(canUpload, canUpload2);

  const [showActionMenu, setShowActionMenu] = React.useState(false);

  console.log(isLoading, Object.keys(workOrderDetails).length);

  return (
    <>
      {isLoading && Object.keys(workOrderDetails).length <= 0 ? (
        <div className="flex h-screen items-center justify-center">
          <ClipLoader color="#fff" size={30} />
        </div>
      ) : (
        <div className="max-w-screen h-full p-4 md:p-4 lg:p-6 xl:p-8">
          <div className="shadow-default mx-auto rounded border border-strokedark bg-boxdark p-5">
            <div className="mb-3 flex w-full items-start justify-between">
              <div className="flex flex-col gap-4">
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-3">
                    <h4 className="text-2xl font-medium text-white">
                      Edit Work Order
                    </h4>
                  </div>
                </div>

                <div className="flex flex-col gap-2">
                  <div className="flex items-center gap-3 text-white">
                    <span className="text-bodydark2">Due Date:</span>
                    <span className="font-medium">
                      {moment(workOrderDetails.due_date).format("MM/DD/YYYY")}
                    </span>
                    <FontAwesomeIcon
                      icon="calendar"
                      className="cursor-pointer text-lg hover:text-primary"
                      onClick={() => setShowWorkOrderSubmissionDatesModal(true)}
                    />
                  </div>
                  <div className="text-white">
                    <span className="text-bodydark2">Auto Approve: </span>
                    <span className="font-medium">
                      {workOrderDetails.auto_approve === 1 ? "Yes" : "No"}
                    </span>
                  </div>
                  <div className="rounded border border-strokedark bg-boxdark-2/40 p-4">
                    <div className="flex flex-row gap-2">
                      <div className="flex justify-between gap-4 text-white">
                        <span className="text-bodydark2">Writer Cost:</span>
                        <span className="font-medium">
                          ${Number(writerCost).toFixed(2)}
                        </span>
                      </div>
                      <div className="flex justify-between gap-4 text-white">
                        <span className="text-bodydark2">Artist Cost:</span>
                        <span className="font-medium">
                          ${Number(artistCost).toFixed(2)}
                        </span>
                      </div>
                      <div className="flex justify-between gap-4 text-white">
                        <span className="text-bodydark2">Engineer Cost:</span>
                        <span className="font-medium">
                          ${Number(engineerCost).toFixed(2)}
                        </span>
                      </div>
                      <div className="ml-2 border-r border-strokedark pl-2">
                        <div className="flex justify-between gap-4 text-white">
                          <span className="font-medium">Total Cost:</span>
                          <span className="font-medium">
                            ${Number(totalCost).toFixed(2)}
                          </span>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>

              {/* 3-dot menu */}
              <div className="flex items-center">
                <button
                  className="inline-flex items-center justify-center rounded-md border border-strokedark bg-meta-4 px-6 py-2.5 text-center font-medium text-white hover:bg-opacity-90"
                  onClick={() => navigate(-1)}
                >
                  Back
                </button>

                <div className="relative">
                  <button
                    onClick={() => setShowActionMenu(!showActionMenu)}
                    className="ml-3 rounded-full p-2 hover:bg-boxdark-2"
                  >
                    <FontAwesomeIcon
                      icon="fa-solid fa-ellipsis-vertical"
                      className="text-lg text-white"
                    />
                  </button>

                  {showActionMenu && (
                    <div className="shadow-default absolute right-0 top-full z-50 mt-2 w-40 rounded border border-stroke bg-boxdark py-2">
                      <button
                        className="flex w-full items-center gap-2 px-4 py-2 text-sm font-medium text-white hover:bg-boxdark-2"
                        onClick={() => {
                          setShowWriterNotesModal(true);
                          setShowActionMenu(false);
                        }}
                      >
                        <FontAwesomeIcon icon="fa-solid fa-note-sticky" />
                        Writer Notes
                      </button>
                      <button
                        className="flex w-full items-center gap-2 px-4 py-2 text-sm font-medium text-danger hover:bg-boxdark-2"
                        onClick={() => {
                          setShowRealDeleteWorkOrderModal(true);
                          setShowActionMenu(false);
                        }}
                      >
                        <FontAwesomeIcon icon="fa-solid fa-trash" />
                        Delete
                      </button>
                    </div>
                  )}
                </div>
              </div>
            </div>

            <div className="my-4 mt-8 overflow-x-auto rounded-md border border-stroke/40 shadow">
              <table className="min-w-full">
                <thead className="bg-meta-4">
                  <tr>
                    {columns.map((column, i) => (
                      <th
                        key={i}
                        scope="col"
                        className="px-6 py-3 text-left text-xs font-medium uppercase tracking-wider text-white"
                      >
                        {column.header}
                      </th>
                    ))}
                  </tr>
                </thead>
                <tbody className="divide-stroke text-white">
                  {tableData.map((row, i) => {
                    return (
                      <tr key={i}>
                        {columns.map((cell, index) => {
                          if (cell.accessor === "create_at") {
                            return (
                              <td
                                key={index}
                                className="whitespace-nowrap px-6 py-4"
                              >
                                {moment(row[cell.accessor])?.format(
                                  "MM/DD/YYYY"
                                )}
                              </td>
                            );
                          }
                          if (cell.accessor === "writer_id") {
                            return (
                              <td
                                key={index}
                                className="whitespace-nowrap px-6 py-4"
                              >
                                {row.writer ? row.writer.name : "N/A"}{" "}
                                {row.status === 1 && (
                                  <FontAwesomeIcon
                                    icon="fa-solid fa-user-pen"
                                    className="ml-2 cursor-pointer text-blue-500"
                                    onClick={(e) => {
                                      e.preventDefault();
                                      setShowModifyWriterModal(true);
                                    }}
                                  />
                                )}
                              </td>
                            );
                          }
                          if (cell.accessor === "artist_id") {
                            return (
                              <td
                                key={index}
                                className="whitespace-nowrap px-6 py-4"
                              >
                                {row.artist ? row.artist.name : "N/A"}{" "}
                                {(row.status === 1 || row.status === 2) && (
                                  <FontAwesomeIcon
                                    icon="fa-solid fa-user-pen"
                                    className="ml-2 cursor-pointer text-blue-500"
                                    onClick={(e) => {
                                      e.preventDefault();
                                      setShowModifyArtistModal(true);
                                    }}
                                  />
                                )}
                              </td>
                            );
                          }
                          if (cell.accessor === "engineer_id") {
                            return (
                              <td
                                key={index}
                                className="whitespace-nowrap px-6 py-4"
                              >
                                {row.engineer ? row.engineer.name : "N/A"}{" "}
                                {(row.status === 1 ||
                                  row.status === 2 ||
                                  row.status === 3) && (
                                  <FontAwesomeIcon
                                    icon="fa-solid fa-user-pen"
                                    className="ml-2 cursor-pointer text-blue-500"
                                    onClick={(e) => {
                                      e.preventDefault();
                                      setShowModifyEngineerModal(true);
                                    }}
                                  />
                                )}
                              </td>
                            );
                          }
                          if (cell.accessor === "status") {
                            console.log(status);
                            console.log(
                              row.auto_approve === 1 &&
                                row.writer_id === row.artist_id &&
                                row.writer_id === row.engineer_id
                            );
                            if (
                              row.auto_approve === 1 &&
                              row.writer_id === row.artist_id &&
                              row.writer_id !== row.engineer_id
                            ) {
                              if (row.status === 1) {
                                return (
                                  <td
                                    key={index}
                                    className="whitespace-nowrap px-6 py-4"
                                  >
                                    Writer/Artist
                                  </td>
                                );
                              } else if (row.status === 3) {
                                return (
                                  <td
                                    key={index}
                                    className="whitespace-nowrap px-6 py-4"
                                  >
                                    Engineer
                                  </td>
                                );
                              } else if (row.status === 5) {
                                return (
                                  <td
                                    key={index}
                                    className="whitespace-nowrap px-6 py-4"
                                  >
                                    Completed
                                  </td>
                                );
                              }
                            }
                            if (
                              row.auto_approve === 1 &&
                              row.writer_id === row.artist_id &&
                              row.writer_id === row.engineer_id
                            ) {
                              if (row.status === 1) {
                                return (
                                  <td
                                    key={index}
                                    className="whitespace-nowrap px-6 py-4"
                                  >
                                    Wri/Art/Eng
                                  </td>
                                );
                              } else if (row.status === 5) {
                                return (
                                  <td
                                    key={index}
                                    className="whitespace-nowrap px-6 py-4"
                                  >
                                    Completed
                                  </td>
                                );
                              }
                            }
                            if (
                              artistAndEngineer &&
                              row.writer_submit_status === 1 &&
                              row.status !== 5 &&
                              status === 2
                            ) {
                              return (
                                <td
                                  key={index}
                                  className="whitespace-nowrap px-6 py-4"
                                >
                                  Artist/Engineer
                                </td>
                              );
                            }
                          }
                          if (cell.mappingExist) {
                            return (
                              <td
                                key={index}
                                className="whitespace-nowrap px-6 py-4"
                              >
                                {cell.mappings[row[cell.accessor]]}
                              </td>
                            );
                          }
                          return (
                            <td
                              key={index}
                              className="whitespace-nowrap px-6 py-4"
                            >
                              {row[cell.accessor]}
                            </td>
                          );
                        })}
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>

            <div
              className={`mb-4 mt-10 flex h-[380px] w-full max-w-full gap-4`}
            >
              <div className="h-full w-1/2">
                {uploadedLoops.length === 0 && (
                  <EmptyLoops
                    canUpload={true}
                    setEmployeeType={handleEmployeeType}
                    setFileUploadType={handleUploadFileType}
                    setFormData={handleLoopUploads}
                    uploadedFilesProgressData={{
                      progress: progressLoops,
                      error: errorLoops,
                      isUploading: isUploadingLoops,
                    }}
                  />
                )}
                {uploadedLoops.length > 0 && (
                  <UploadedLoops
                    uploadedFilesProgressData={{
                      progress: progressLoops,
                      error: errorLoops,
                      isUploading: isUploadingLoops,
                    }}
                    canUpload={true}
                    uploadedFiles={uploadedLoops}
                    setDeleteFileId={handleDeleteFileSubmit}
                    setEmployeeType={handleEmployeeType}
                    setFileUploadType={handleUploadFileType}
                    setFormData={handleLoopUploads}
                  />
                )}
              </div>
              <div className="h-full w-1/2">
                {" "}
                {uploadedSessions.length > 0 ? (
                  <UploadedSessions
                    canUpload={true}
                    uploadedFilesProgressData={{ progress, error, isUploading }}
                    uploadedFiles={uploadedSessions}
                    setDeleteFileId={handleDeleteFileSubmit}
                    setEmployeeType={handleEmployeeType}
                    setFileUploadType={handleUploadFileType}
                    setFormData={handleSessionUploads}
                  />
                ) : (
                  <EmptySessions
                    uploadedFilesProgressData={{ progress, error, isUploading }}
                    canUpload={true}
                    setEmployeeType={handleEmployeeType}
                    setFileUploadType={handleUploadFileType}
                    setFormData={handleSessionUploads}
                  />
                )}
              </div>
            </div>

            {status && status === 1 && (
              <WorkOrderWriter
                subProjects={subProjects}
                workOrderDetails={workOrderDetails}
                setLyrics={handleUpdateLyrics}
                setDeleteFileId={handleDeleteFileSubmit}
                setApproveWorkOrder={handleApproveWorkOrder}
              />
            )}
            {status && status === 2 && !artistAndEngineer && (
              <WorkOrderArtist
                sessions={sessions}
                subProjects={subProjects}
                workOrderDetails={workOrderDetails}
                setDeleteFileId={handleDeleteFileSubmit}
                setLyrics={handleUpdateLyrics}
              />
            )}
            {console.log(status, artistAndEngineer, "ednndnd")}
            {status && status === 3 && !artistAndEngineer && (
              <WorkOrderEngineer
                sessions={sessions}
                subProjects={subProjects}
                workOrderDetails={workOrderDetails}
                setLyrics={handleUpdateLyrics}
                setDeleteFileId={handleDeleteFileSubmit}
                setCompleteWorkOrder={handleCompleteWorkOrder}
              />
            )}
            {status && status === 2 && artistAndEngineer && (
              <WorkOrderArtistEngineer
                sessions={sessions}
                subProjects={subProjects}
                workOrderDetails={workOrderDetails}
                setDeleteFileId={handleDeleteFileSubmit}
                setLyrics={handleUpdateLyrics}
                setCompleteWorkOrder={handleCompleteWorkOrder}
              />
            )}
            {status && status === 11 && (
              <WorkOrderWriterArtist
                sessions={sessions}
                subProjects={subProjects}
                workOrderDetails={workOrderDetails}
                setLyrics={handleUpdateLyrics}
                setDeleteFileId={handleDeleteFileSubmit}
              />
            )}
            {status && status === 12 && (
              <WorkOrderWriterArtistEngineer
                sessions={sessions}
                subProjects={subProjects}
                workOrderDetails={workOrderDetails}
                setLyrics={handleUpdateLyrics}
                setDeleteFileId={handleDeleteFileSubmit}
              />
            )}
            {status && status === 5 && (
              <WorkOrderCompleted
                sessions={sessions}
                subProjects={subProjects}
                workOrderDetails={workOrderDetails}
                setLyrics={handleUpdateLyrics}
                setDeleteFileId={handleDeleteFileSubmit}
              />
            )}

            <button
              className="mt-4 rounded bg-primary px-4 py-[12px] font-bold text-white hover:bg-primary/90"
              type="button"
              onClick={(e) => {
                e.preventDefault();
                handleSaveAll();
              }}
            >
              Save All
            </button>
          </div>
        </div>
      )}

      {showDeleteWorkOrderModal ? (
        <ConfirmModal
          confirmText={`Are you sure you want to delete this work order? This action cannot be undone.`}
          setModalClose={handleDeleteWorkOrderModalClose}
          setFormYes={handleRealDeleteWorkOrder}
        />
      ) : null}

      {showNoteModal ? (
        <AddNoteModal
          setModalClose={handleNoteModalClose}
          setFormData={handleSubmitNote}
        />
      ) : null}

      {showViewNoteModal ? (
        <ViewNoteModal note={note} setModalClose={handleViewNoteModalClose} />
      ) : null}

      {showRealDeleteWorkOrderModal ? (
        <DuoConfirmModal
          confirmText={`Are you sure you want to delete this work order?`}
          setModalClose={handleRealDeleteWorkOrderModalClose}
          setFormYes={openSecondDelete}
        />
      ) : null}

      {showModifyWriterModal ? (
        <ModifyWriterModal
          writers={writers}
          selectedWriterId={selectedWriterId}
          setModalClose={handleModifyWriterModalClose}
          setFormSubmit={handleModifySubProjectWriter}
        />
      ) : null}

      {showModifyArtistModal ? (
        <ModifyArtistModal
          artists={artists}
          selectedArtistId={selectedArtistId}
          setModalClose={handleModifyArtistModalClose}
          setFormSubmit={handleModifySubProjectArtist}
        />
      ) : null}

      {showModifyEngineerModal ? (
        <ModifyEngineerModal
          engineers={engineers}
          selectedEngineerId={selectedEngineerId}
          setModalClose={handleModifyEngineerModalClose}
          setFormSubmit={handleModifySubProjectEngineer}
        />
      ) : null}

      {showWriterNotesModal ? (
        <WriterNotesModal
          notes={workOrderDetails.writer_notes}
          setModalClose={handleWriterNotesModalClose}
        />
      ) : null}

      {showWorkOrderSubmissionDatesModal ? (
        <WorkOrderSubmission
          data={submissionData}
          setModalClose={handleWorkorderSubmitModalClose}
        />
      ) : null}
    </>
  );
};

export default EditWorkOrderPage;
