import ConfirmModal from "Components/Modal/ConfirmModal";
import EmptySessions from "Components/PublicWorkOrder/ArtistWorkOrder/EmptySessions";
import UploadedSessions from "Components/PublicWorkOrder/ArtistWorkOrder/UploadedSessions";
import { jsPDF } from "jspdf";
import JSZip from "jszip";
import moment from "moment-timezone";
import React from "react";
import { useNavigate } from "react-router-dom";
import { ClipLoader } from "react-spinners";
import { GlobalContext, showToast } from "Src/globalContext";
import { useS3Upload } from "Src/libs/uploads3Hook";
import { sendEmailAPIV3 } from "Src/services/emailService";
import { deleteOneFileAPI } from "Src/services/projectService";
import {
  deleteS3FileAPI,
  getAllWriterFilesByWorkOrderIdAPI,
  getWorkOrderPublicDetailsAPI,
  updateWorkOrderAPI,
  uploadFilesDataAPI,
} from "Src/services/workOrderService";
import {
  dateTimeToFormattedString,
  resetSubProjectsChronology,
  validateUuidv4,
} from "Utils/utils";

const ArtistWorkOrderPage = () => {
  const {
    dispatch: globalDispatch,
    state: { subproject_update },
  } = React.useContext(GlobalContext);
  const { uploadS3FilesAPI, progress, error, isUploading } = useS3Upload();
  const navigate = useNavigate();

  const [isLoading, setIsLoading] = React.useState(false);
  const [canUpload, setCanUpload] = React.useState(false);
  const [uploadedLoops, setUploadedLoops] = React.useState([]);
  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 [adminInstrumentalFiles, setAdminInstrumentalFiles] = React.useState(
    []
  );
  const [combinedLyrics, setCombinedLyrics] = React.useState([]);

  const [showSubmitWorkOrderModal, setShowSubmitWorkOrderModal] =
    React.useState(false);

  const [writerSubmitStatus, setWriterSubmitStatus] = React.useState(false);
  const [projectsInfo, setProjectsInfo] = React.useState([]); // [{project_id, team_name, program_name}

  const [downloadCancelToken, setDownloadCancelToken] = React.useState(null);
  const [isDownloading, setIsDownloading] = React.useState(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 handleSubmitWorkOrderModalClose = () => {
    setShowSubmitWorkOrderModal(false);
  };

  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 {
      // let existingDueDate = moment(workOrderDetails.due_date).format(
      //   'MM/DD/YYYY hh:mm:ss a'
      // );
      // let engineerDueDate = moment(existingDueDate).add(
      //   workOrderDetails.engineer_deadline
      //     ? Number(workOrderDetails.engineer_deadline)
      //     : 0,
      //   'days'
      // );
      // engineerDueDate = moment(engineerDueDate).format('MM/DD/YYYY hh:mm:ss a');

      let currentDay = moment().format("MM/DD/YYYY");
      let engineerDueDate = moment(currentDay).add(
        workOrderDetails.engineer_deadline
          ? Number(workOrderDetails.engineer_deadline)
          : 0,
        "days"
      );
      engineerDueDate = moment(engineerDueDate).format("YYYY-MM-DD");

      const result = await updateWorkOrderAPI({
        id: Number(workOrderDetails.id),
        artist_submit_status: 1,
        due_date: engineerDueDate,
        status: 3,
        artist_submission_datetime: moment()
          .tz("America/New_York")
          .format("YYYY-MM-DD HH:mm:ss"),
      });

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

        if (subProjects.length > 0) {
          subProjects = resetSubProjectsChronology(subProjects);
        }

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

        let emailSubject = `Engineer Work Order ${workOrderDetails.workorder_code}: ${workOrderDetails.writer.name} for ${workOrderDetails.artist.name} has been placed by ${workOrderDetails.user_company_name}`;

        let body = `
        Due Date: ${dateTimeToFormattedString(engineerDueDate)}
        <br><br>An order for you to engineer has been placed. Files have been attached. Please upload master files using this link: ${workOrderLink}.
        <br><br>Number of Voiceovers: ${voiceOverCount}.
        <br><br>Number of Songs: ${songCount}.
        <br><br>Total Number of 8-counts: ${totalEightCount}.`;

        let payload = {
          from: "myeq@equalityrecords.com",
          to: workOrderDetails.engineer.email,
          subject: emailSubject,
          body: body,
        };

        const result = await sendEmailAPIV3(payload);

        if (!result.error) {
          showToast(globalDispatch, result.message, 5000);
          handleSubmitWorkOrderModalClose();
          window.location.reload();
        } else {
          showToast(globalDispatch, result.message, 5000, "error");
          return;
        }
      } 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");
    }
  };

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

      // Process writer files from the demos array

      console.log(subProjects);
      adminInstrumentalFiles.forEach((instrumental) => {
        idLinkArray.push({ id: instrumental.id, link: instrumental.url });
      });

      writerFiles
        .filter((subproject) => subproject.type != "demo")
        .forEach((elem) => {
          idLinkArray.push({ id: elem.id, link: elem.url });
        });
      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 });
          }
        });

        // 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 downloadFilesByWebLinks = async (
    idLinkArray,
    combinedLyrics,
    zipFileName
  ) => {
    let progressDiv = null;
    let handleDiv = null;
    const controller = new AbortController();
    setDownloadCancelToken(controller);

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

    // Define drag functions
    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
    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 for drag functionality
      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();
          if (progressDiv && document.body.contains(progressDiv)) {
            document.body.removeChild(progressDiv);
          }
          setIsDownloading(false);
          setDownloadCancelToken(null);
          showToast(globalDispatch, "Download cancelled", 5000);
          return;
        }
      };

      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) {
        if (controller.signal.aborted) {
          return;
        }

        const chunk = idLinkArray.slice(i, i + CHUNK_SIZE);
        await Promise.all(
          chunk.map(
            async ({ id, link, lyrics, program, team_name, type_name }) => {
              if (controller.signal.aborted) {
                return;
              }

              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(
                    sanitizeText(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(sanitizeText(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(); // Add cleanup call here
        document.body.removeChild(progressDiv);
      }
    }
  };

  //  const getSubProjectsByProjectId = async () => {
  //    try {
  //      const result = await getSubProjectsByProjectIdAPI(Number(params?.id));
  //      if (!result.error) {
  //        // sort subProjects by type_name
  //        // type_name = 'Voiceover 3', 'Song 2', 'Voiceover 1', 'Voiceover 4', 'Song 1'
  //        // i want to sort it like this
  //     //    if (result.list.length > 0) {
  //     //      let sortedSubProjects = sortSubProjectsAscByTypeName(result.list);

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

  // const downloadLyrics = async (combinedLyrics) => {
  //   if (combinedLyrics.length > 0) {
  //     let lyrics = '';
  //     combinedLyrics.forEach((row) => {
  //       lyrics += `${row.program}_${row.team_name}\nType: ${
  //         row.type_name
  //       }\nLyrics:\n${row.lyrics ? row.lyrics : 'N/A'}\n`;
  //     });
  //     const pdfBlob = await generatePdfBlob(lyrics);
  //     const pdfLink = document.createElement('a');
  //     pdfLink.href = URL.createObjectURL(pdfBlob);
  //     pdfLink.download = `WorkOrder_${
  //       workOrderDetails.workorder_code
  //     }_${moment().format('HH:mm:ss_DD-MM-YYYY')}.pdf`;
  //     pdfLink.click();
  //   }
  // };

  const generateLyricsText = (combinedLyrics) => {
    let lyrics = "";
    combinedLyrics.forEach((row) => {
      if (row.lyrics) {
        // First clean up the lyrics by properly handling <br> tags and trimming
        row.lyrics = replaceBrTagToNextLine(row.lyrics).trim();

        // Ensure there's no trailing comma and the text is complete
        lyrics += `${row.program}_${row.team_name}\nType: ${
          row.type_name
        }\nLyrics:\n${row.lyrics ? row.lyrics : "N/A"}\n\n`;
      }
    });
    return lyrics.trim(); // Trim the final string to remove any trailing whitespace
  };

  const replaceBrTagToNextLine = (text) => {
    // First replace <br> tags with newlines
    let processedText = text.replace(/<br\s*\/?>/gi, "\n");
    // Remove any trailing commas
    processedText = processedText.replace(/,\s*$/, "");
    // Split by newlines, trim each line, and rejoin
    return processedText
      .split("\n")
      .map((line) => line.trim())
      .filter((line) => line) // Remove empty lines
      .join("\n");
  };

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

  // Function to generate a PDF blob from text using jsPDF
  const generatePdfBlob = async (text) => {
    const doc = new jsPDF();
    const lines = doc.splitTextToSize(text, 180); // Split text into lines to fit within the page width
    doc.text(lines, 10, 10);
    return doc.output("blob");
  };

  const generatePdfBlobCombined = async (lyricsText) => {
    const doc = new jsPDF();
    const pageHeight = doc.internal.pageSize.height;
    const lineHeight = 7;
    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;
    };

    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");
      doc.setFontSize(12);
      doc.setFont(undefined, "bold");
      addTextToPDF(header);

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

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

  React.useEffect(() => {
    const url = new URL(window.location.href);
    const uuidv4 = url.pathname.split("/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: "artist",
          });
          if (!result.error) {
            if (!result.model.artist_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)
            );

            let projects = [];
            let adminInstrumentalFiles = [];
            if (
              result.model.sub_projects &&
              result.model.sub_projects.length > 0
            ) {
              // find unique projects from sub_projects->project_id, team_name, program_name

              result.model.sub_projects.forEach((row) => {
                let project = projects.find(
                  (project) => project.project_id === row.project_id
                );
                if (!project) {
                  projects.push({
                    project_id: row.project_id,
                    team_name: row.team_name,
                    program_name: row.program_name,
                  });
                }
                if (row.admin_writer_instrumentals) {
                  row.admin_writer_instrumentals.forEach((instrumental) => {
                    adminInstrumentalFiles.push(instrumental);
                  });
                }
              });
            }

            setAdminInstrumentalFiles(adminInstrumentalFiles);

            setProjectsInfo(projects);
            setUploadedLoops(result.model.instrumentals);
            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]);

  return (
    <>
      {isLoading ? (
        <div className="flex h-screen items-center justify-center">
          <ClipLoader color="#fff" size={30} />
        </div>
      ) : (
        <div className="mt-16 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 text-2xl font-semibold text-white">
              Work Order - {workOrderDetails.workorder_code}:{" "}
              {workOrderDetails.writer ? workOrderDetails.writer.name : ""} for{" "}
              {workOrderDetails.artist?.name}
            </h5>
            <button
              className="rounded bg-primary px-4 py-2 font-medium text-white hover:bg-primary/80 disabled:cursor-not-allowed disabled:opacity-50"
              type="button"
              disabled={isDownloading}
              onClick={(e) => {
                e.preventDefault();
                handleDownloadFiles();
              }}
            >
              Download Files Uploaded by Writer
            </button>
          </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
                uploadedFilesProgressData={{ progress, error, isUploading }}
                canUpload={canUpload}
                uploadedFiles={uploadedSessions}
                setDeleteFileId={handleDeleteFileSubmit}
                setEmployeeType={handleEmployeeType}
                setFileUploadType={handleUploadFileType}
                setFormData={handleSessionUploads}
              />
            ) : (
              <EmptySessions
                canUpload={canUpload}
                uploadedFilesProgressData={{ progress, error, isUploading }}
                setEmployeeType={handleEmployeeType}
                setFileUploadType={handleUploadFileType}
                setFormData={handleSessionUploads}
              />
            )}
          </div>

          {projectsInfo.length > 0 && (
            <div className="mb-2 block h-full w-full max-w-5xl rounded-md border border-gray-500 bg-gray-800 p-5 shadow">
              <div className="flex flex-col">
                <div className="mb-4 text-lg font-semibold text-white">
                  Projects in this work order
                </div>

                {/* <div className='text-white'>
                  {projectsInfo.map((row, index) => {
                    return (
                      <div
                        key={index}
                        className='flex flex-col mb-2 text-white'
                      >{`${row.program_name} - ${row.team_name}`}</div>
                    );
                  })}
                </div> */}

                {/* add a bullet point list */}
                <ul className="list-inside list-disc text-white">
                  {projectsInfo.map((row, index) => {
                    return (
                      <li
                        key={index}
                      >{`${row.program_name} - ${row.team_name}`}</li>
                    );
                  })}
                </ul>
              </div>
            </div>
          )}

          {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
              </div>
            </div>
          )}
        </div>
      )}

      {showSubmitWorkOrderModal ? (
        <ConfirmModal
          confirmText={
            uploadedSessions.length <= 0 ? (
              <div>
                <p>The following information is missing:</p>
                <ul className="list-disc">
                  <li>Session files</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 ArtistWorkOrderPage;
