import EmptySessions from "Components/PublicWorkOrder/ArtistWorkOrder/EmptySessions";
import UploadedSessions from "Components/PublicWorkOrder/ArtistWorkOrder/UploadedSessions";
import EngineerSubProjects from "Components/PublicWorkOrder/EngineerWorkOrder/EngineerSubProjects";
import { jsPDF } from "jspdf";
import JSZip from "jszip";
import moment from "moment-timezone";
import React from "react";
import { useNavigate } from "react-router-dom";
import { GlobalContext, showToast } from "Src/globalContext";
import {
  deleteOneFileAPI,
  updateSubProjectDetailsAPI,
} from "Src/services/projectService";
import {
  replaceBrTagToNextLine,
  resetSubProjectsChronology,
  validateUuidv4,
} from "Utils/utils";

import ConfirmModal from "Components/Modal/ConfirmModal";
import { ClipLoader } from "react-spinners";
import { useS3Upload } from "Src/libs/uploads3Hook";
import {
  deleteS3FileAPI,
  getAllWriterFilesByWorkOrderIdAPI,
  getWorkOrderPublicDetailsAPI,
  updateWorkOrderAPI,
  uploadFilesDataAPI,
} from "Src/services/workOrderService";

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

  const navigate = useNavigate();
  const { uploadS3FilesAPI, progress, error, isUploading } = useS3Upload();
  const [isLoading, setIsLoading] = React.useState(false);
  const [canUpload, setCanUpload] = React.useState(false);
  const [uploadedSessions, setUploadedSessions] = React.useState([]);
  const [subProjects, setSubProjects] = React.useState([]);
  const [workOrderDetails, setWorkOrderDetails] = React.useState({});
  const [employeeType, setEmployeeType] = React.useState("");
  const [fileType, setFileType] = React.useState("");
  const [employeeId, setEmployeeId] = React.useState(null);

  const [writerFiles, setWriterFiles] = React.useState([]);
  const [combinedLyrics, setCombinedLyrics] = React.useState([]);
  const [isDownloading, setIsDownloading] = React.useState(false);
  const [showSubmitWorkOrderModal, setShowSubmitWorkOrderModal] =
    React.useState(false);

  const [writerSubmitStatus, setWriterSubmitStatus] = React.useState(false);
  const [downloadCancelToken, setDownloadCancelToken] = React.useState(null);

  console.log(subProjects.length);
  const handleSubmitWorkOrderModalClose = () => {
    setShowSubmitWorkOrderModal(false);
  };

  const sanitizeText = (text) => {
    if (!text) return "";

    // Method 1: Basic cleanup using encodeURIComponent/decodeURIComponent
    try {
      text = decodeURIComponent(encodeURIComponent(text));
    } catch (e) {
      console.warn("Failed to encode/decode text:", e);
    }

    // Method 2: Remove common problematic characters
    text = text
      .replace(/[\uFFFD\uFEFF\u200B]/g, "") // Remove replacement char, zero-width spaces, etc
      .replace(/[^\x20-\x7E\n\r\t]/g, "") // Keep only basic ASCII + newlines
      .replace(/\u00A0/g, " ") // Replace non-breaking spaces with regular spaces
      .trim();

    return text;
  };

  const handleSubmitWorkOrderModalOpen = () => {
    setShowSubmitWorkOrderModal(true);
  };

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

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

  const handleSubmitWorkOrder = async () => {
    try {
      const result = await updateWorkOrderAPI({
        id: Number(workOrderDetails.id),
        artist_submit_status: 1,
        engineer_submit_status: 1,
        status: 5,
        is_viewed: 0,
        artist_engineer_submission_datetime: moment()
          .tz("America/New_York")
          .format("YYYY-MM-DD HH:mm:ss"),
      });

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

  const getAllWriterFilesByWorkOrderId = async (Id) => {
    try {
      const result = await getAllWriterFilesByWorkOrderIdAPI(Id);
      if (!result.error) {
        setWriterFiles(result.list);
        if (result.lyrics && result.lyrics.length > 0) {
          setCombinedLyrics(result.lyrics);
        }
      }
    } catch (error) {
      showToast(globalDispatch, error.message, 5000, "error");
    }
  };

  const handleDownloadFiles = async () => {
    try {
      let idLinkArray = []; // Array to hold objects with IDs and links
      let hasLyrics = false;

      writerFiles
        .filter((subproject) => subproject.type != "demo")
        .forEach((elem) => {
          idLinkArray.push({ id: elem.id, link: elem.url });
        });
      // Process writer files from the demos array
      subProjects.forEach((subproject) => {
        subproject.demos.forEach((demo) => {
          if (demo.employee_type === "writer") {
            idLinkArray.push({ id: subproject.id, link: demo.url });
          }
        });
        subproject.admin_writer_instrumentals.forEach((demo) => {
          if (demo.employee_type === "writer") {
            idLinkArray.push({ id: subproject.id, link: demo.url });
          }
        });

        // adminInstrumentalFiles.forEach((instrumental) => {
        //   idLinkArray.push({ id: subproject.id, link: instrumental.url });
        // });

        //  adminInstrumentalFiles.forEach((instrumental) => {
        //    idLinkArray.push({ id: subproject.id, link: instrumental.url });
        //  });

        // Check if subproject has lyrics
        if (subproject.lyrics) {
          hasLyrics = true;
          idLinkArray.push({
            id: subproject.id,
            link: subproject.lyrics,
            lyrics: subproject.lyrics,
            program: subproject.program_name,
            team_name: subproject.team_name,
            type_name: subproject.type_name,
          });
        }
      });

      // Check if combined lyrics are available
      if (combinedLyrics.length > 0) {
        hasLyrics = true;
      }

      if (idLinkArray.length === 0) {
        showToast(
          globalDispatch,
          "No files uploaded by writer yet. Downloading Lyrics only if available.",
          5000,
          "error"
        );
        if (hasLyrics) {
          await downloadLyrics(combinedLyrics);
        }
        return;
      } else {
        const zipFileName = `Work_order_${
          workOrderDetails.workorder_code
        }_writer_files_${moment().format("HH:mm:ss_DD-MM-YYYY")}`;
        showToast(globalDispatch, "File download has started", 5000);
        await downloadFilesByWebLinks(idLinkArray, combinedLyrics, zipFileName);
      }
    } catch (error) {
      showToast(globalDispatch, error.message, 5000, "error");
    }
  };

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

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

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

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

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

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

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

  const downloadLyrics = async (combinedLyrics) => {
    if (combinedLyrics.length > 0) {
      let lyrics = "";
      // combinedLyrics.lyrics may contain <br> tag. So, we need to replace it with \n
      combinedLyrics.forEach((row) => {
        if (row.lyrics) {
          // row.lyrics = row.lyrics.replace(/<br\s*\/?>/gi, '\n');
          row.lyrics = replaceBrTagToNextLine(row.lyrics);
        }
        lyrics += `${row.program}_${row.team_name}\nType: ${
          row.type_name
        }\nLyrics:\n${row.lyrics ? row.lyrics : "N/A"}\n`;
      });

      const pdfBlob = await generatePdfBlob(sanitizeText(lyrics));
      const pdfLink = document.createElement("a");
      pdfLink.href = URL.createObjectURL(pdfBlob);
      pdfLink.download = `WorkOrder_${
        workOrderDetails.workorder_code
      }_writer_files_${moment().format("HH:mm:ss_DD-MM-YYYY")}.pdf`;
      pdfLink.click();
    }
  };

  const downloadFilesByWebLinks = async (
    idLinkArray,
    combinedLyrics,
    zipFileName
  ) => {
    let progressDiv = null;
    let handleDiv = null;
    const controller = new AbortController();
    setDownloadCancelToken(controller);

    // Define drag state variables outside
    let isDragging = false;
    let currentX;
    let currentY;
    let initialX;
    let initialY;
    let xOffset = 0;
    let yOffset = 0;

    // Define all drag functions outside try block
    const dragStart = (e) => {
      if (e.type === "touchstart") {
        initialX = e.touches[0].clientX - xOffset;
        initialY = e.touches[0].clientY - yOffset;
      } else {
        initialX = e.clientX - xOffset;
        initialY = e.clientY - yOffset;
      }

      if (e.target === handleDiv || e.target === progressDiv) {
        isDragging = true;
      }
    };

    const dragEnd = () => {
      isDragging = false;
    };

    const drag = (e) => {
      if (isDragging) {
        e.preventDefault();

        if (e.type === "touchmove") {
          currentX = e.touches[0].clientX - initialX;
          currentY = e.touches[0].clientY - initialY;
        } else {
          currentX = e.clientX - initialX;
          currentY = e.clientY - initialY;
        }

        xOffset = currentX;
        yOffset = currentY;

        progressDiv.style.transform = `translate(${currentX}px, ${currentY}px)`;
      }
    };

    // Define cleanup function outside try block
    const cleanup = () => {
      if (!progressDiv) return;
      progressDiv.removeEventListener("mousedown", dragStart);
      document.removeEventListener("mousemove", drag);
      document.removeEventListener("mouseup", dragEnd);
      progressDiv.removeEventListener("touchstart", dragStart);
      document.removeEventListener("touchmove", drag);
      document.removeEventListener("touchend", dragEnd);
    };

    try {
      setIsDownloading(true);
      const zip = new JSZip();
      const totalFiles = idLinkArray.length;
      let downloadedFiles = 0;

      // Create progress element with draggable functionality
      progressDiv = document.createElement("div");
      progressDiv.style.position = "fixed";
      progressDiv.style.top = "50%";
      progressDiv.style.left = "50%";
      progressDiv.style.transform = "translate(-50%, -50%)";
      progressDiv.style.background = "rgba(0, 0, 0, 0.8)";
      progressDiv.style.padding = "20px";
      progressDiv.style.borderRadius = "10px";
      progressDiv.style.color = "white";
      progressDiv.style.zIndex = "1000";
      progressDiv.style.minWidth = "200px";
      progressDiv.style.textAlign = "center";
      progressDiv.style.cursor = "move";
      progressDiv.style.userSelect = "none";

      // Create handle div for dragging
      handleDiv = document.createElement("div");
      handleDiv.style.position = "absolute";
      handleDiv.style.top = "0";
      handleDiv.style.left = "0";
      handleDiv.style.right = "0";
      handleDiv.style.height = "30px";
      handleDiv.style.cursor = "move";
      handleDiv.style.borderTopLeftRadius = "10px";
      handleDiv.style.borderTopRightRadius = "10px";

      // Add event listeners
      progressDiv.addEventListener("mousedown", dragStart);
      document.addEventListener("mousemove", drag);
      document.addEventListener("mouseup", dragEnd);
      progressDiv.addEventListener("touchstart", dragStart);
      document.addEventListener("touchmove", drag);
      document.addEventListener("touchend", dragEnd);

      const progressContent = document.createElement("div");
      progressContent.style.marginTop = "10px";
      progressContent.style.wordBreak = "break-word";

      const cancelButton = document.createElement("button");
      cancelButton.innerHTML = "✕";
      cancelButton.style.position = "absolute";
      cancelButton.style.right = "10px";
      cancelButton.style.top = "5px";
      cancelButton.style.background = "none";
      cancelButton.style.border = "none";
      cancelButton.style.color = "white";
      cancelButton.style.cursor = "pointer";
      cancelButton.style.fontSize = "16px";
      cancelButton.style.zIndex = "1001";

      cancelButton.onclick = () => {
        if (window.confirm("Are you sure you want to cancel the download?")) {
          controller.abort();
          showToast(globalDispatch, "Download cancelled", 5000);
        }
      };

      progressDiv.appendChild(handleDiv);
      progressDiv.appendChild(cancelButton);
      progressDiv.appendChild(progressContent);
      document.body.appendChild(progressDiv);

      const updateProgress = (current, total, filename) => {
        const percentage = Math.round((current / total) * 100);
        progressContent.innerHTML = `
          Downloading: ${percentage}%<br>
          ${filename}<br>
          (${current}/${total} files)
        `;
      };

      // Group files by subproject
      const subprojects = {};

      // Process files in chunks
      const CHUNK_SIZE = 5;
      for (let i = 0; i < idLinkArray.length; i += CHUNK_SIZE) {
        const chunk = idLinkArray.slice(i, i + CHUNK_SIZE);
        await Promise.all(
          chunk.map(
            async ({ id, link, lyrics, program, team_name, type_name }) => {
              const subproject = subProjects.find((sp) => sp.id === id);
              const subprojectName = subproject?.type
                ? `${subproject.type}: ${subproject.program_name} ${subproject.team_name}`
                : "Sessions";

              if (!subprojects[subprojectName]) {
                subprojects[subprojectName] = [];
              }

              try {
                if (lyrics) {
                  // Handle lyrics - create PDF directly
                  updateProgress(
                    downloadedFiles,
                    totalFiles,
                    `Lyrics_${type_name}:${program}_${team_name}`
                  );
                  const lyricsText = `${program}_${team_name}\nType: ${type_name}\nLyrics:\n${
                    lyrics ? lyrics : "N/A"
                  }\n\n`;
                  const pdfBlob = await generatePdfBlob(lyricsText);
                  subprojects[subprojectName].push({
                    fileName: `Lyrics_${type_name}:${program}_${team_name}.pdf`,
                    blob: pdfBlob,
                  });
                } else {
                  // Handle regular file download
                  const fileName = link.split("/").pop();
                  updateProgress(downloadedFiles, totalFiles, fileName);

                  const response = await fetch(link, {
                    signal: controller.signal,
                  });
                  if (!response.ok)
                    throw new Error(`HTTP error! status: ${response.status}`);
                  const blob = await response.blob();

                  subprojects[subprojectName].push({ fileName, blob });
                }
                downloadedFiles++;
                updateProgress(
                  downloadedFiles,
                  totalFiles,
                  lyrics ? `Lyrics_${subprojectName}_` : link.split("/").pop()
                );
              } catch (error) {
                console.error(
                  `Failed to process ${lyrics ? "lyrics" : link}:`,
                  error
                );
                showToast(
                  globalDispatch,
                  `Failed to process file`,
                  5000,
                  "error"
                );
              }
            }
          )
        );
      }

      // Add files to zip maintaining folder structure
      for (const [subprojectName, files] of Object.entries(subprojects)) {
        const folder = zip.folder(subprojectName);
        for (const { fileName, blob } of files) {
          folder.file(fileName, blob);
        }
      }

      // Handle combined lyrics if present
      if (combinedLyrics.length > 0) {
        progressDiv.innerHTML = "Processing combined lyrics...";
        let lyrics = "";
        combinedLyrics.forEach((row) => {
          if (row.lyrics) {
            row.lyrics = replaceBrTagToNextLine(row.lyrics);
          }
          lyrics += `${row.program}_${row.team_name}\nType: ${
            row.type_name
          }\nLyrics:\n${row.lyrics ? row.lyrics : "N/A"}\n\n`;
        });
        const pdfBlob = await generatePdfBlobCombined(lyrics);
        zip.file("Combined_Lyrics.pdf", pdfBlob);
      }

      progressDiv.innerHTML = "Generating ZIP file...";
      const zipBlob = await zip.generateAsync({ type: "blob" });

      document.body.removeChild(progressDiv);
      const zipLink = document.createElement("a");
      zipLink.href = URL.createObjectURL(zipBlob);
      zipLink.download = `${zipFileName}.zip`;
      zipLink.click();
      URL.revokeObjectURL(zipLink.href);
    } catch (error) {
      if (error.name === "AbortError") {
        return;
      }
      console.error("Download failed:", error);
      showToast(
        globalDispatch,
        "Download failed: " + error.message,
        5000,
        "error"
      );
    } finally {
      setIsDownloading(false);
      setDownloadCancelToken(null);
      if (progressDiv && document.body.contains(progressDiv)) {
        cleanup();
        document.body.removeChild(progressDiv);
      }
    }
  };

  const generatePdfBlob = async (text) => {
    const doc = new jsPDF();
    const lines = doc.splitTextToSize(text, 180);
    doc.text(lines, 10, 10);
    return doc.output("blob");
  };

  React.useEffect(() => {
    const url = new URL(window.location.href);
    const uuidv4 = url.pathname.split("/engineer-artist/")[1];

    if (!uuidv4) {
      showToast(globalDispatch, "Invalid URL", 5000, "error");
      navigate("/");
    } else {
      const checkUuidv4 = validateUuidv4(uuidv4);
      if (!checkUuidv4) {
        showToast(globalDispatch, "Invalid URL", 5000, "error");
        navigate("/");
      } else {
        (async function () {
          const result = await getWorkOrderPublicDetailsAPI({
            uuidv4,
            employee_type: "engineer_artist",
          });
          if (!result.error) {
            if (
              !result.model.artist_submit_status &&
              !result.model.engineer_submit_status
            ) {
              setCanUpload(true);
            }

            if (result.model.writer_submit_status) {
              setWriterSubmitStatus(true);
            }

            setWorkOrderDetails(result.model);
            // setSubProjects(result.model.sub_projects);
            setSubProjects(
              resetSubProjectsChronology(result.model.sub_projects)
            );
            setUploadedSessions(result.model.sessions);
            await getAllWriterFilesByWorkOrderId(result.model.id);
            setIsLoading(false);
          } else {
            showToast(globalDispatch, result.message, 5000, "error");
            setIsLoading(false);
            window.location.href = "/member/login";
          }
        })();
      }
    }
  }, [subproject_update]);

  const masters = subProjects.reduce((accumulator, subproject) => {
    return accumulator + subproject.masters.length;
  }, 0);

  const Lyrics = subProjects.filter((subproject) => {
    return !subproject.lyrics;
  });

  const songDetails = subProjects.filter((subproject) => {
    return (
      subproject.is_song &&
      (!subproject.bpm || !subproject.song_key || !subproject.type_name)
    );
  });

  const handleUpdateSubProjectDetails = async (payload) => {
    try {
      setIsLoading(true);
      const result = await updateSubProjectDetailsAPI(payload);
      if (!result.error) {
        showToast(
          globalDispatch,
          "Sub-project details updated successfully",
          5000
        );
        setIsLoading(false);
        window.location.reload();
      } else {
        showToast(globalDispatch, result.message, 5000, "error");
        setIsLoading(false);
      }
    } catch (error) {
      showToast(globalDispatch, error.message, 5000, "error");
    }
  };

  return (
    <>
      {isLoading ? (
        <div className="flex h-screen items-center justify-center">
          <ClipLoader color="#fff" size={30} />
        </div>
      ) : (
        <div className="my-8 flex flex-col items-center justify-center gap-4">
          <div className="flex w-full max-w-5xl flex-row flex-wrap justify-between">
            <h5 className="text-md mb-2 items-center font-semibold text-white">
              Work Order - {workOrderDetails.workorder_code}:{" "}
              {workOrderDetails.writer ? workOrderDetails.writer.name : ""} for{" "}
              {workOrderDetails.artist ? workOrderDetails.artist.name : ""}
            </h5>
            <button
              className="rounded bg-primary px-4 py-2 font-bold text-white hover:bg-primary/90 disabled:cursor-not-allowed disabled:opacity-50"
              type="button"
              disabled={isDownloading}
              onClick={(e) => {
                e.preventDefault();
                handleDownloadFiles();
              }}
            >
              {isDownloading
                ? "Downloading..."
                : "Download Files Uploaded by Writer"}
            </button>
          </div>

          {/* <div className='flex flex-row flex-wrap justify-between mt-4 w-full max-w-5xl'>
            <h5 className='items-center font-semibold text-white text-md'>
              Demo Files Uploaded by the writer
            </h5>
          </div> */}

          {/* work order details */}
          <div className="mb-2 block h-[320px] w-full max-w-5xl rounded bg-boxdark p-5 shadow">
            {uploadedSessions.length > 0 ? (
              <UploadedSessions
                canUpload={canUpload}
                uploadedFiles={uploadedSessions}
                uploadedFilesProgressData={{ progress, error, isUploading }}
                setDeleteFileId={handleDeleteFileSubmit}
                setEmployeeType={handleEmployeeType}
                setFileUploadType={handleUploadFileType}
                setFormData={handleSessionUploads}
              />
            ) : (
              <EmptySessions
                canUpload={canUpload}
                uploadedFilesProgressData={{ progress, error, isUploading }}
                setEmployeeType={handleEmployeeType}
                setFileUploadType={handleUploadFileType}
                setFormData={handleSessionUploads}
              />
            )}
          </div>

          {/* master files */}
          <div className="mt-4 flex w-full max-w-5xl flex-row flex-wrap justify-between">
            <h5 className="text-md items-center font-semibold text-white">
              Master Files
            </h5>
          </div>
          {/* subprojects */}
          <EngineerSubProjects
            isPublic={true}
            canUpload={canUpload}
            subProjects={subProjects}
            workOrderDetails={workOrderDetails}
            setDeleteFileId={handleDeleteFileSubmit}
            setSubProjectDetails={handleUpdateSubProjectDetails}
          />

          {canUpload && writerSubmitStatus && (
            <div className="flex w-full max-w-5xl flex-row flex-wrap justify-end">
              <button
                className="w-[220px] rounded bg-primary px-6 py-4 font-bold text-white hover:bg-primary"
                type="button"
                onClick={(e) => {
                  e.preventDefault();

                  handleSubmitWorkOrderModalOpen();
                }}
              >
                Submit
              </button>
            </div>
          )}
          {!writerSubmitStatus && (
            <div className="flex flex-col">
              <div className="mb-2 text-center text-xl font-semibold text-white">
                You do not have permission to upload because workorder has not
                yet submitted by the writer.
              </div>
            </div>
          )}
          {!canUpload && (
            <div className="flex flex-col">
              <div className="mb-2 text-center text-xl font-semibold text-white">
                Workorder Submitted by Artist/Engineer
              </div>
            </div>
          )}
        </div>
      )}

      {showSubmitWorkOrderModal ? (
        <ConfirmModal
          confirmText={
            uploadedSessions.length <= 0 ||
            masters === 0 ||
            Lyrics.length > 0 ||
            songDetails.length > 0 ? (
              <div>
                <p>The following information is missing:</p>
                <ul className="list-disc">
                  {uploadedSessions.length === 0 && <li>Session files</li>}
                  {masters === 0 && <li>Master files</li>}
                  {Lyrics.length > 0 && <li>Lyrics</li>}
                  {songDetails.length > 0 && <li>Song Details Field</li>}
                </ul>
                <p>Would you like to continue work order submission?</p>
              </div>
            ) : (
              "Are you sure you want to submit this work order?"
            )
          }
          setModalClose={handleSubmitWorkOrderModalClose}
          setFormYes={handleSubmitWorkOrder}
        />
      ) : null}
    </>
  );
};

export default ArtistEngineerWorkOrderPage;
