import React from "react";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import moment from "moment-timezone";
import ArtistSubProject from "./ArtistSubProject";
import ArtistSessionFiles from "./ArtistSessionFiles";
import { GlobalContext, showToast } from "Src/globalContext";
import { sendEmailAPIV3 } from "Src/services/emailService";
import {
  uploadS3FilesAPI,
  uploadFilesDataAPI,
  updateWorkOrderAPI,
} from "Src/services/workOrderService";
import { updateSubProjectDetailsAPI } from "Src/services/projectService";
import {
  copyLinkToClipboard,
  dateTimeToFormattedString,
  resetSubProjectsChronology,
} from "Utils/utils";
import ConfirmModal from "Components/Modal/ConfirmModal";

const WorkOrderArtist = ({
  sessions,
  subProjects,
  workOrderDetails,
  setLyrics,
  setDeleteFileId,
}) => {
  const {
    dispatch: globalDispatch,
    state: { subproject_update },
  } = React.useContext(GlobalContext);
  const [showCompleteWorkOrderModal, setShowCompleteWorkOrderModal] =
    React.useState(false);
  const [showCompleteWorkOrderModal2, setShowCompleteWorkOrderModal2] =
    React.useState(false);

  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 handleCompleteWorkOrderBtnSubmit = () => {
    setShowCompleteWorkOrderModal2(true);
    setShowCompleteWorkOrderModal(false);
  };

  const handleCompleteWorkOrderBtnSubmit2 = async () => {
    try {
      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);
          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");
    } finally {
      setShowCompleteWorkOrderModal2(false);
    }
  };

  const handleCompleteWorkOrderModalClose2 = () => {
    setShowCompleteWorkOrderModal2(false);
  };

  const handleCompleteWorkOrderModalClose = () => {
    setShowCompleteWorkOrderModal(false);
  };

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

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

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

      // employee_name,link,voiceover_count,eight_count,contents
      let emailSubject = `Artist Work Order ${workOrderDetails.workorder_code}: ${workOrderDetails.writer.name} for ${workOrderDetails.artist.name} has been placed by ${workOrderDetails.user.company_name}`;
      const workOrderLink = `https://equalityrecords.com/work-order/artist/${workOrderDetails.uuidv4}`;
      let body = `Due Date: ${dateTimeToFormattedString(
        workOrderDetails.due_date
      )}
        <br><br>An order for you to record has been placed. Below are the lyrics and demos for each team. Please upload your session files using this link: ${workOrderLink}.
        <br><br>Number of Voiceovers: ${voiceOverCount}.
        <br><br>Number of Songs: ${songCount}.
        <br><br>Total Number of 8-counts: ${totalEightCount}.<br>`;
      let payload = {
        from: "myeq@equalityrecords.com",
        to: workOrderDetails.artist.email,
        subject: emailSubject,
        body: body,
      };
      const result = await sendEmailAPIV3(payload);
      if (!result.error) {
        showToast(globalDispatch, result.message, 5000);
        return;
      } else {
        showToast(globalDispatch, result.message, 5000, "error");
        return;
      }
    } catch (error) {}
  };

  const copyLinkToClipboardTrigger = (link) => {
    try {
      const result = copyLinkToClipboard(link);
      if (result) {
        showToast(globalDispatch, "Link copied to clipboard", 3000, "info");
      } else {
        showToast(globalDispatch, "Copy failed", 3000, "error");
      }
    } catch (error) {
      console.error(error);
      showToast(globalDispatch, "Copy failed", 3000, "error");
    }
  };

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

  return (
    <>
      {window.location.pathname.includes("edit-work-order") ? null : (
        <ArtistSessionFiles
          uploadedFiles={sessions}
          setDeleteFileId={setDeleteFileId}
          setFormData={handleSessionUploads}
        />
      )}
      <div className="flex flex-col gap-3">
        {subProjects &&
          subProjects.length > 0 &&
          subProjects.map((subProject, index) => {
            return (
              <ArtistSubProject
                key={index}
                workOrderDetails={workOrderDetails}
                subProject={subProject}
                uploadedDemoFiles={subProject.demos}
                setLyrics={setLyrics}
                setDeleteFileId={setDeleteFileId}
                setSubProjectDetails={handleUpdateSubProjectDetails}
              />
            );
          })}
      </div>

      <div className="flex flex-row">
        <div className="flex w-1/2 flex-row justify-start">
          <button
            className="focus:shadow-outline mt-2 w-max rounded bg-primary px-4 py-2 text-sm font-bold text-white hover:bg-primary/80 focus:outline-none"
            type="button"
            onClick={(e) => {
              e.preventDefault();
              handleResendArtistEmail();
            }}
          >
            Resend Email to Artist
          </button>
          <div
            className="focus:shadow-outline ml-1 mt-2 flex w-max cursor-pointer items-center justify-center rounded bg-primary px-2 py-2 text-sm font-bold text-white hover:bg-primary/90 focus:outline-none"
            onClick={() =>
              copyLinkToClipboardTrigger(
                `https://equalityrecords.com/work-order/artist/${workOrderDetails.uuidv4}`
              )
            }
          >
            <FontAwesomeIcon icon="fa-solid fa-link" height={12} />
          </div>
        </div>
        <div className="flex w-1/2 flex-row justify-end gap-2">
          <button
            className="focus:shadow-outline mt-2 w-[220px]  rounded bg-primary px-6 py-4 text-sm font-bold text-white hover:bg-primary/80 focus:outline-none"
            type="button"
            onClick={(e) => {
              e.preventDefault();
              setShowCompleteWorkOrderModal(true);
            }}
          >
            Complete
          </button>
        </div>
      </div>

      {showCompleteWorkOrderModal2 ? (
        <ConfirmModal
          confirmText={`Are you sure you want to push the status of this work order?. This cannot be undone.`}
          setModalClose={handleCompleteWorkOrderModalClose2}
          setFormYes={handleCompleteWorkOrderBtnSubmit2}
        />
      ) : null}

      {showCompleteWorkOrderModal ? (
        <ConfirmModal
          confirmText={`Are you sure you want to push the status of this work order?`}
          setModalClose={handleCompleteWorkOrderModalClose}
          setFormYes={handleCompleteWorkOrderBtnSubmit}
        />
      ) : null}
    </>
  );
};

export default WorkOrderArtist;
