import React from "react";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import moment from "moment-timezone";
import { AuthContext, tokenExpireError } from "Src/authContext";
import { GlobalContext, showToast } from "Src/globalContext";
import { sendEmailAPIV3 } from "Src/services/emailService";
import { updateWorkOrderAPI } from "Src/services/workOrderService";
import { updateSubProjectDetailsAPI } from "Src/services/projectService";
import { uploadFilesDataAPI } from "Src/services/workOrderService";
import WriterArtistEngineerSubProject from "./WriterArtistEngineerSubProject";
import SessionFiles from "./SessionFiles";
import SendNote from "Components/WorkOrder/Writer/SendNote";
import {
  copyLinkToClipboard,
  dateTimeToFormattedString,
  resetSubProjectsChronology,
} from "Utils/utils";
import { useS3Upload } from "Src/libs/uploads3Hook";
import ConfirmModal from "Components/Modal/ConfirmModal";

const WorkOrderWriterArtistEngineer = ({
  sessions,
  subProjects,
  workOrderDetails,
  setLyrics,
  setDeleteFileId,
}) => {
  console.log(subProjects);
  const { dispatch } = React.useContext(AuthContext);
  const {
    dispatch: globalDispatch,
    state: { subproject_update },
  } = React.useContext(GlobalContext);
  const { uploadS3FilesAPI, progress, error, isUploading } = useS3Upload();

  console.log(subproject_update);

  const [isLoading, setIsLoading] = React.useState(false);
  const [showSendNote, setShowSendNote] = React.useState(false);
  const [showCompleteWorkOrderModal, setShowCompleteWorkOrderModal] =
    React.useState(false);
  const [showCompleteWorkOrderModal2, setShowCompleteWorkOrderModal2] =
    React.useState(false);

  const handleShowSendNoteClose = () => {
    setShowSendNote(false);
  };

  const handleCompleteWorkOrderBtnSubmit = () => {
    setShowCompleteWorkOrderModal2(true);
    setShowCompleteWorkOrderModal(false);
  };

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

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

  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 handleUpdateWorkOrder = async () => {
    try {
      const result = await updateWorkOrderAPI({
        id: Number(workOrderDetails.id),
        writer_submit_status: 0,
        status: 1,
        is_viewed: 0,
      });

      if (!result.error) {
        showToast(globalDispatch, result.message, 5000);
        return true;
      } else {
        showToast(globalDispatch, result.message, 5000);
        return false;
      }
    } catch (error) {
      tokenExpireError(dispatch, error.message);
    }
  };

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

      if (!result.error) {
        showToast(globalDispatch, result.message, 5000, "success");
        globalDispatch({
          type: "SET_SUBPROJECT_UPDATE",
          payload: !subproject_update,
        });
      } else {
        showToast(globalDispatch, result.message, 5000, "error");
        return;
      }
    } catch (error) {
      showToast(globalDispatch, error.message, 5000, "error");
    } finally {
      setShowCompleteWorkOrderModal2(false);
    }
  };

  const handleNoteSubmit = async (note) => {
    try {
      const workOrderWriterLink = `https://equalityrecords.com/work-order/writer/${workOrderDetails.uuidv4}`;
      let emailSubject = `REVISION for Work Order ${workOrderDetails.workorder_code}: ${workOrderDetails.writer.name} for ${workOrderDetails.artist.name} has been placed by ${workOrderDetails.user.company_name}`;
      setShowSendNote(false);
      let payload = {
        from: "myeq@equalityrecords.com",
        to: workOrderDetails.writer.email,
        subject: emailSubject,
        body: `Note: ${note}<br><br>Work Order link: ${workOrderWriterLink}`,
      };
      const result = await sendEmailAPIV3(payload);
      if (!result.error) {
        const workOrderResult = await handleUpdateWorkOrder();
        if (workOrderResult) {
          showToast(globalDispatch, result.message, 5000);
          globalDispatch({
            type: "SET_SUBPROJECT_UPDATE",
            payload: !subproject_update,
          });
          return;
        } else {
          showToast(
            globalDispatch,
            "Something went wrong. Please try again later.",
            5000,
            "error"
          );
          return;
        }
      } else {
        showToast(globalDispatch, result.message, 5000, "error");
        return;
      }
    } catch (error) {}
  };

  const handleResendWriterArtistEngineerEmail = async () => {
    try {
      if (workOrderDetails.sub_projects.length > 0) {
        workOrderDetails.sub_projects = resetSubProjectsChronology(
          workOrderDetails.sub_projects
        );
      }

      setIsLoading(true);
      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) {
          songCount++;
        }
        totalEightCount += subProject.eight_count;
      });

      let emailSubject = `Writing Artist Engineer Work Order ${workOrderDetails.workorder_code}: ${workOrderDetails.writer.name} for ${workOrderDetails.artist.name} has been placed by ${workOrderDetails.user.company_name}`;
      const workOrderWriterLink = `https://equalityrecords.com/work-order/writer-artist-engineer/${workOrderDetails.uuidv4}`;
      let body = `Due Date: ${dateTimeToFormattedString(
        workOrderDetails.due_date
      )}
        <br><br>An order for your writing artist engineer has been placed. Below are the notes for each team from the coach and the producer. Please upload your session, lyrics and master using this link: ${workOrderWriterLink}.
        <br><br>Number of Voiceovers: ${voiceOverCount}.
        <br>Number of Songs: ${songCount}.
        <br><br>Total Number of 8-counts: ${totalEightCount}
        <br><br>
        ${
          workOrderDetails.sub_projects.length > 0
            ? workOrderDetails.sub_projects
                .map((row) => {
                  return `<b><u>${row.type}: ${row.program_name} - ${
                    row.team_name
                  }</u></b><br>
                  Number of 8-counts: ${row.eight_count}<br>
                  Team Type: ${
                    (Number(row.team_type) === 1 && "All Girl") ||
                    (Number(row.team_type) === 2 && "Co-ed") ||
                    (Number(row.team_type) === 3 && "TBD")
                  }<br>
                  Theme: ${
                    row.survey.theme_of_the_routine
                      ? row.survey.theme_of_the_routine
                      : "N/A"
                  }<br>
                  Division: ${row.division}<br>
                  Colors: ${row.colors}<br>
                  Notes: <br>${
                    row.ideas && row.ideas.length > 0
                      ? `<ul>${row.ideas
                          .map(
                            (idea) =>
                              `<li>${idea.idea_value
                                .split("\n")
                                .join("<br>")}</li>`
                          )
                          .join("")}</ul><br>`
                      : "N/A<br><br>"
                  }<br><br>`;
                })
                .join("")
            : "N/A"
        }
        <br>
        `;
      let payload = {
        from: "myeq@equalityrecords.com",
        to: workOrderDetails.writer.email,
        subject: emailSubject,
        body: body,
      };
      const result = await sendEmailAPIV3(payload);
      if (!result.error) {
        setIsLoading(false);
        showToast(globalDispatch, result.message, 5000);
        return;
      } else {
        setIsLoading(false);
        showToast(globalDispatch, result.message, 5000, "error");
        return;
      }
    } catch (error) {
      setIsLoading(false);
      tokenExpireError(dispatch, error.message);
    }
  };

  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 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);
          console.log(!subproject_update);
          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");
    }
  };

  return (
    <>
      {window.location.pathname.includes("edit-work-order") ? null : (
        <SessionFiles
          uploadedFilesProgressData={{ progress, error, isUploading }}
          uploadedFiles={sessions}
          setDeleteFileId={setDeleteFileId}
          setFormData={handleSessionUploads}
        />
      )}

      <div className="flex flex-col gap-3">
        {subProjects &&
          subProjects.length > 0 &&
          subProjects.map((subProject, index) => {
            return (
              <WriterArtistEngineerSubProject
                key={index}
                workOrderDetails={workOrderDetails}
                subProject={subProject}
                uploadedMasterFiles={subProject.masters}
                setLyrics={setLyrics}
                setDeleteFileId={setDeleteFileId}
                setSubProjectDetails={handleUpdateSubProjectDetails}
              />
            );
          })}
      </div>

      <div className="flex w-full flex-row justify-between">
        <div className="flex w-1/2 flex-row justify-start">
          {!isLoading ? (
            <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();
                handleResendWriterArtistEngineerEmail();
              }}
            >
              Resend Email to Wri/Art/Eng
            </button>
          ) : (
            <button
              className="focus:shadow-outline mt-2 w-max rounded bg-yellow-500 px-4 py-2 text-sm font-bold text-white hover:bg-yellow-600 focus:outline-none"
              type="button"
              disabled
            >
              Sending Email...
            </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/writer-artist-engineer/${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>

      {showSendNote && (
        <SendNote
          setNoteSubmit={handleNoteSubmit}
          setSendNoteClose={handleShowSendNoteClose}
        />
      )}

      {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 WorkOrderWriterArtistEngineer;
