import ConfirmModal from "Components/Modal/ConfirmModal";
import EmptyLoops from "Components/PublicWorkOrder/WriterWorkOrder/EmptyLoops";
import SubProjects from "Components/PublicWorkOrder/WriterWorkOrder/SubProjects";
import UploadedLoops from "Components/PublicWorkOrder/WriterWorkOrder/UploadedLoops";
import moment from "moment-timezone";
import React, { useState } 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 { useS3UploadMaster } from "Src/libs/uploads3HookMaster";
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 WriterWorkOrderPage = () => {
  const { dispatch: globalDispatch, state } = React.useContext(GlobalContext);
  const { subproject_update } = state;

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

  const navigate = useNavigate();

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

  console.log("djdjdjjd", "po", subproject_update);

  // useEffect(() => {
  //   globalDispatch({
  //     type: "SET_SUB_PROJECT_LYRICS",
  //     payload: [
  //       ...subProjectLyrics,
  //       {
  //         subproject_id: subProjectId,
  //         lyrics: e.target.value,
  //       },
  //     ],
  //   });
  // });

  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 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);
          console.log("ji");
          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 payload = {
        id: Number(workOrderDetails.id),
        employee_id: Number(employeeId),
        writer_submit_status: 1,
        writer_submission_datetime: moment()
          .tz("America/New_York")
          .format("YYYY-MM-DD HH:mm:ss"),
      };

      if (
        workOrderDetails.auto_approve &&
        Number(workOrderDetails.auto_approve) === 1
      ) {
        let currentDate = moment().format("MM/DD/YYYY");
        let localDueDate = "";
        if (workOrderDetails.artist_id === workOrderDetails.engineer_id) {
          localDueDate = moment(currentDate).add(
            workOrderDetails.artist_engineer_deadline,
            "days"
          );
        }
        localDueDate = moment(currentDate).add(
          workOrderDetails.artist_deadline,
          "days"
        );
        localDueDate = moment(localDueDate).format("YYYY-MM-DD");
        payload = {
          id: Number(workOrderDetails.id),
          employee_id: Number(employeeId),
          writer_submit_status: 1,
          due_date: localDueDate,
          status: 2,
          writer_submission_datetime: moment()
            .tz("America/New_York")
            .format("YYYY-MM-DD HH:mm:ss"),
        };
      }

      const result = await updateWorkOrderAPI(payload);

      if (!result.error) {
        if (
          workOrderDetails.auto_approve &&
          Number(workOrderDetails.auto_approve) === 1
        ) {
          if (workOrderDetails.artist_id === workOrderDetails.engineer_id) {
            console.log("dnndnd");
            await handleTriggerEmailToArtistEngineer();
          } else {
            console.log("dndn");
            await handleTriggerEmailToArtist();
          }
          window.location.reload();
        } else {
          showToast(globalDispatch, result.message, 5000);
          globalDispatch({
            type: "SET_SUBPROJECT_UPDATE",
            payload: !subproject_update,
          });
          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 handleTriggerEmailToArtist = 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 artistDueDate = moment(currentDate).add(
      workOrderDetails.artist_deadline,
      "days"
    );
    artistDueDate = moment(artistDueDate).format("YYYY-MM-DD");

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

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

    const workOrderArtistLink = `https://equalityrecords.com/work-order/artist/${workOrderDetails.uuidv4}`;

    let htmlBody = `Due Date: ${dateTimeToFormattedString(artistDueDate)}
          <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: ${workOrderArtistLink}.
          <br><br>Number of Voiceovers: ${voiceOverCount}.
          <br>Number of Songs: ${songCount}.
          <br><br>Total Number of 8-counts: ${totalEightCount}.
          <br><br>
          `;

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

    const emailResult = await sendEmailAPIV3(payload);

    if (!emailResult.error) {
      setIsLoading(false);
      showToast(
        globalDispatch,
        "Email sent to the artist as writer is auto approved.",
        5000
      );
      window.location.reload();
    } else {
      setIsLoading(false);
      showToast(globalDispatch, emailResult.message, 5000, "error");
      return;
    }
  };

  const handleTriggerEmailToArtistEngineer = 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 artistEngineerDueDate = moment(currentDate).add(
      workOrderDetails.artist_engineer_deadline,
      "days"
    );
    artistEngineerDueDate = moment(artistEngineerDueDate).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;
      });

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

    const workOrderArtistEngineerLink = `https://equalityrecords.com/work-order/engineer-artist/${workOrderDetails.uuidv4}`;

    let htmlBody = `Due Date: ${dateTimeToFormattedString(
      artistEngineerDueDate
    )}
          <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: ${workOrderArtistEngineerLink}.
          <br><br>Number of Voiceovers: ${voiceOverCount}.
          <br>Number of Songs: ${songCount}.
          <br><br>Total Number of 8-counts: ${totalEightCount}.
          <br><br>
          `;

    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 artist as writer is auto approved.",
        5000
      );
      globalDispatch({
        type: "SET_SUBPROJECT_UPDATE",
        payload: !subproject_update,
      });
    } else {
      setIsLoading(false);
      showToast(globalDispatch, emailResult.message, 5000, "error");
      return;
    }
  };

  const handleSaveAll = async () => {
    try {
      await handleSaveAllLyrics();
      await handleSaveAllSubProjectDetails();
    } catch (error) {
      showToast(globalDispatch, error.message, 5000, "error");
    }
  };

  const handleSaveAllLyrics = async () => {
    try {
      // subProjectLyrics
      // [{
      //    subproject_id: subProjectId,
      //    lyrics: e.target.value,
      // }]
      // setIsLoading(true);
      // 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();
      } else {
        showToast(globalDispatch, "Error updating lyrics", 5000, "error");
      }
      globalDispatch({
        type: "SET_SUBPROJECT_UPDATE",
        payload: !subproject_update,
      });
      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/")[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 () {
          setIsLoading(true);
          const result = await getWorkOrderPublicDetailsAPI({
            uuidv4,
            employee_type: "writer",
          });
          if (!result.error) {
            setIsLoading(false);
            if (!result.model.writer_submit_status) {
              setCanUpload(true);
            }

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

  console.log(subProjects);

  // const demos = subProjects.map((subproject) => {
  //   return subproject.demos;
  // });

  const demos = subProjects.reduce((accumulator, subproject) => {
    return accumulator + subproject.demos.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)
    );
  });

  //

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

  return (
    <>
      {isLoading && Object.keys(workOrderDetails).length <= 0 ? (
        <div className="flex justify-center items-center h-screen">
          <ClipLoader color="#fff" size={30} />
        </div>
      ) : (
        <div className="flex flex-col gap-4 justify-center items-center my-8">
          <div className="flex flex-row flex-wrap justify-between w-full max-w-5xl h-full">
            <h5 className="items-center mb-2 text-2xl font-semibold text-white text-md">
              Work Order - {workOrderDetails.workorder_code}:{" "}
              {workOrderDetails?.writer_name} for{" "}
              {workOrderDetails.artist ? workOrderDetails.artist.name : ""}
            </h5>
          </div>
          <div className="h-[320px] w-[64rem] max-w-5xl">
            {uploadedLoops.length === 0 && (
              <EmptyLoops
                canUpload={canUpload}
                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={canUpload}
                uploadedFiles={uploadedLoops}
                setDeleteFileId={handleDeleteFileSubmit}
                setEmployeeType={handleEmployeeType}
                setFileUploadType={handleUploadFileType}
                setFormData={handleLoopUploads}
              />
            )}
          </div>

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

          {canUpload && (
            <div className="flex flex-row flex-wrap justify-between w-full max-w-5xl">
              <button
                className="px-6 py-2 font-bold text-white rounded bg-primary 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,
                    });
                  }

                  handleSubmitWorkOrderModalOpen();
                }}
              >
                Submit
              </button>
            </div>
          )}
          {!canUpload && (
            <div className="flex flex-col">
              <div className="mb-2 text-xl font-semibold text-center text-white">
                Workorder Submitted by Writer
              </div>
            </div>
          )}
        </div>
      )}

      {showSubmitWorkOrderModal ? (
        <ConfirmModal
          confirmText={
            uploadedLoops.length <= 0 ||
            demos === 0 ||
            Lyrics.length > 0 ||
            songDetails.length > 0 ? (
              <div>
                <p>The following information is missing:</p>
                <ul className="list-disc">
                  {uploadedLoops.length === 0 && (
                    <li>Loops for writing files</li>
                  )}
                  {demos === 0 && <li>Demo 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 WriterWorkOrderPage;
