import ConfirmModal from "Components/Modal/ConfirmModal";
import EmptySessions from "Components/PublicWorkOrder/WriterArtistWorkOrder/EmptySessions";
import SubProjects from "Components/PublicWorkOrder/WriterArtistWorkOrder/SubProjects";
import UploadedSessions from "Components/PublicWorkOrder/WriterArtistWorkOrder/UploadedSessions";
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,
  updateSubProjectDetailsAPI,
} from "Src/services/projectService";
import {
  deleteS3FileAPI,
  getWorkOrderPublicDetailsAPI,
  updateLyricsPublicAPI,
  updateWorkOrderAPI,
  uploadFilesDataAPI,
} from "Src/services/workOrderService";
import {
  dateTimeToFormattedString,
  resetSubProjectsChronology,
  validateUuidv4,
} from "Utils/utils";

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

  const { subProjectLyrics, songSubProjects } = state;

  const navigate = useNavigate();

  const [isLoading, setIsLoading] = React.useState(false);
  const [canUpload, setCanUpload] = React.useState(false);
  const [subProjects, setSubProjects] = React.useState([]);
  const [workOrderDetails, setWorkOrderDetails] = React.useState({});
  const [uploadedSessions, setUploadedSessions] = React.useState([]);
  const [showSubmitWorkOrderModal, setShowSubmitWorkOrderModal] =
    React.useState(false);

  const handleSubmitWorkOrderModalClose = () => {
    setShowSubmitWorkOrderModal(false);
  };

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

  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 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 currentDate = moment().format("MM/DD/YYYY");

      let engineerDueDate = moment(currentDate).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),
        employee_id: Number(workOrderDetails.writer_id),
        writer_submit_status: 1,
        artist_submit_status: 1,
        due_date: engineerDueDate,
        status: 3,
        writer_artist_submission_datetime: moment()
          .tz("America/New_York")
          .format("YYYY-MM-DD HH:mm:ss"),
      });

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

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

  const handleTriggerEmailToEngineer = async () => {
    let subProjects = workOrderDetails.sub_projects;
    let voiceOverCount = 0;
    let songCount = 0;
    let totalEightCount = 0;

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

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

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

    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 htmlBody = `
    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}.`;

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

    const emailResult = await sendEmailAPIV3(payload);

    if (!emailResult.error) {
      setIsLoading(false);
      showToast(
        globalDispatch,
        "Email sent to the engineer as the workorder is auto approved.",
        5000
      );
      globalDispatch({
        type: "SET_SUBPROJECT_UPDATE",
        payload: !subproject_update,
      });
    } else {
      setIsLoading(false);
      showToast(globalDispatch, emailResult.message, 5000, "error");
      return;
    }
  };

  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 handleSaveAll = async () => {
    try {
      await handleSaveAllLyrics();
      await handleSaveAllSubProjectDetails();
      globalDispatch({
        type: "SET_SUBPROJECT_UPDATE",
        payload: !subproject_update,
      });
    } catch (error) {
      showToast(globalDispatch, error.message, 5000, "error");
    }
  };

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

      // if (subProjectLyrics.length === 0) {
      //   showToast(
      //     globalDispatch,
      //     "No changes found to update the all lyrics",
      //     5000,
      //     "warning"
      //   );
      //   setIsLoading(false);
      //   return;
      // }

      const updateLyricsPromises = subProjectLyrics.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,
      // }]
      // setIsLoading(true);
      // if (songSubProjects.length === 0) {
      //   showToast(
      //     globalDispatch,
      //     "No changes found to update the all sub project details",
      //     5000,
      //     "warning"
      //   );
      //   setIsLoading(false);
      //   return;
      // }

      const updateSubProjectDetailsPromises = songSubProjects.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
        );
        // window.location.reload();
      } else {
        showToast(
          globalDispatch,
          "Error updating all sub-project details",
          5000,
          "error"
        );
      }
      setIsLoading(false);
    } catch (error) {
      showToast(globalDispatch, error.message, 5000, "error");
    }
  };

  React.useEffect(() => {
    const url = new URL(window.location.href);
    const uuidv4 = url.pathname.split("/writer-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: "writer",
          });
          if (!result.error) {
            setIsLoading(false);
            if (
              !result.model.writer_submit_status &&
              result.model.auto_approve === 1
            ) {
              if (
                result.model.writer_id === result.model.artist_id &&
                result.model.writer_id !== result.model.engineer_id
              ) {
                setCanUpload(true);
              }
            }

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

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

  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 text-2xl font-semibold text-white">
              Work Order - {workOrderDetails.workorder_code}:{" "}
              {workOrderDetails.writer?.name} for{" "}
              {workOrderDetails.artist ? workOrderDetails.artist.name : ""}
            </h5>
          </div>

          {/* session files */}

          <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}
                setFormData={handleSessionUploads}
              />
            ) : (
              <EmptySessions
                uploadedFilesProgressData={{ progress, error, isUploading }}
                canUpload={canUpload}
                setFormData={handleSessionUploads}
              />
            )}
          </div>

          <SubProjects
            canUpload={canUpload}
            subProjects={subProjects}
            workOrderDetails={workOrderDetails}
            setLyrics={handleUpdateLyrics}
            setDeleteFileId={handleDeleteFileSubmit}
            setSubProjectDetails={handleUpdateSubProjectDetails}
          />

          {canUpload && (
            <div className="flex w-full max-w-5xl flex-row flex-wrap justify-between">
              <button
                className="rounded bg-primary px-6 py-2 font-bold text-white hover:bg-primary/90"
                type="button"
                onClick={(e) => {
                  e.preventDefault();
                  handleSaveAll();
                }}
              >
                Save All
              </button>
              <button
                className="w-[220px] rounded bg-primary px-6 py-4 font-bold text-white hover:bg-primary"
                type="button"
                onClick={async (e) => {
                  e.preventDefault();
                  if (subProjectLyrics.length > 0) {
                    await handleSaveAllLyrics();
                    console.log("pop");
                    globalDispatch({
                      type: "SET_SUBPROJECT_UPDATE",
                      payload: !subproject_update,
                    });
                    console.log("poeooe");
                  }
                  if (songSubProjects.length > 0) {
                    await handleSaveAllSubProjectDetails();
                    globalDispatch({
                      type: "SET_SUBPROJECT_UPDATE",
                      payload: !subproject_update,
                    });
                  }
                  await handleSubmitWorkOrderModalOpen();
                }}
              >
                Submit
              </button>
            </div>
          )}
          {!canUpload && (
            <div className="flex flex-col">
              <div className="mb-2 text-center text-xl font-semibold text-white">
                Workorder Submitted by Writer
              </div>
            </div>
          )}
        </div>
      )}

      {showSubmitWorkOrderModal ? (
        <ConfirmModal
          confirmText={
            uploadedSessions.length <= 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>}
                  {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 WriterArtistWorkOrderPage;
