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 {
  deleteS3FileAPI,
  updateWorkOrderAPI,
  uploadFilesDataAPI,
} from "Src/services/workOrderService";
import {
  deleteOneFileAPI,
  updateSubProjectDetailsAPI,
} from "Src/services/projectService";
import WriterSubProject from "./WriterSubProject";
import SendNote from "Components/WorkOrder/Writer/SendNote";
import ConfirmModal from "Components/Modal/ConfirmModal";
import {
  copyLinkToClipboard,
  dateTimeToFormattedString,
  resetSubProjectsChronology,
} from "Utils/utils";
import { render } from "@fullcalendar/core/preact";
import { date } from "yup";
import EmptyLoops from "Components/PublicWorkOrder/WriterWorkOrder/EmptyLoops";
import UploadedLoops from "Components/PublicWorkOrder/WriterWorkOrder/UploadedLoops";
import { useS3Upload } from "Src/libs/uploads3Hook";

const WorkOrderWriter = ({
  subProjects,
  workOrderDetails,
  setLyrics,
  setDeleteFileId,
  setApproveWorkOrder,
}) => {
  const { dispatch } = React.useContext(AuthContext);
  const { dispatch: globalDispatch, state } = React.useContext(GlobalContext);
  console.log(workOrderDetails);
  const [employeeType, setEmployeeType] = React.useState("");
  const { subproject_update } = state;
  const [fileType, setFileType] = React.useState("");
  const [employeeId, setEmployeeId] = React.useState(null);
  const [canUpload, setCanUpload] = React.useState(
    !workOrderDetails.writer_submit_status ? true : false
  );
  const [uploadedLoops, setUploadedLoops] = React.useState(
    workOrderDetails.instrumentals
  );
  const [isLoading, setIsLoading] = React.useState(false);
  const [showSendNote, setShowSendNote] = React.useState(false);
  const { uploadS3FilesAPI, progress, error, isUploading } = useS3Upload();
  const { subProjectLyrics, songSubProjects } = state;
  const [showApproveWorkOrderModal, setShowApproveWorkOrderModal] =
    React.useState(false);

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

  const handleDenyBtnClick = (e) => {
    e.preventDefault();
    setShowSendNote(true);
  };

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

  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,
        });
        setIsLoading(false);
      } 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 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 handleApproveWorkOrderModalClose = () => {
    setShowApproveWorkOrderModal(false);
  };

  const handleApproveWorkOrderSubmit = () => {
    setApproveWorkOrder(true);
  };

  console.log(workOrderDetails, "work");

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

  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
      );
      globalDispatch({
        type: "SET_SUBPROJECT_UPDATE",
        payload: !subproject_update,
      });
    } 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 handleCompleteWorkOrderBtnSubmit2 = 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) {
            await handleTriggerEmailToArtistEngineer();
          } else {
            await handleTriggerEmailToArtist();
          }
        } else {
          showToast(globalDispatch, result.message, 5000);
          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 handleCompleteWorkOrderModalClose2 = () => {
    setShowCompleteWorkOrderModal2(false);
  };

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

  const handleResendWriterEmail = 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 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/${workOrderDetails.uuidv4}`;
      let body = `Due Date: ${dateTimeToFormattedString(
        workOrderDetails.due_date
      )}
        <br><br>An order for your writing has been placed. Below are the notes for each team from the coach and the producer. Please upload your demos and lyrics 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.program_name} - ${row?.team_name}`
                      : "Unassigned"
                  }</u></b><br>
                  Number of 8-counts: ${row.eight_count || "N/A"}<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 || "N/A"}<br>
                  Colors: ${row.colors || "N/A"}<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>`
                      : `${row.notes || "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 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 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: 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);
          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");
    }
  };

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

      <div className="flex flex-row justify-between w-full">
        <div className="flex flex-row justify-start w-1/2">
          {!isLoading ? (
            <button
              className="px-4 py-2 mt-2 w-max text-sm font-bold text-white rounded focus:shadow-outline bg-primary hover:bg-primary/80 focus:outline-none"
              type="button"
              onClick={(e) => {
                e.preventDefault();
                handleResendWriterEmail();
              }}
            >
              Resend Email to Writer
            </button>
          ) : (
            <button
              className="px-4 py-2 mt-2 w-max text-sm font-bold text-white bg-yellow-500 rounded focus:shadow-outline hover:bg-yellow-600 focus:outline-none"
              type="button"
              disabled
            >
              Sending Email...
            </button>
          )}
          <div
            className="flex justify-center items-center px-2 py-2 mt-2 ml-1 w-max text-sm font-bold text-white rounded cursor-pointer focus:shadow-outline bg-primary hover:bg-primary/90 focus:outline-none"
            onClick={() =>
              copyLinkToClipboardTrigger(
                `https://equalityrecords.com/work-order/writer/${workOrderDetails.uuidv4}`
              )
            }
          >
            <FontAwesomeIcon icon="fa-solid fa-link" height={12} />
          </div>
        </div>

        {workOrderDetails.writer_submit_status &&
        Number(workOrderDetails.writer_submit_status) === 1 ? (
          <div className="flex flex-row gap-2 justify-end w-1/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();
                setShowApproveWorkOrderModal(true);
              }}
            >
              Approve
            </button>
            <button
              className="focus:shadow-outline mt-2 w-[220px] rounded bg-danger px-6 py-4 text-sm font-bold text-white hover:bg-danger/80 focus:outline-none"
              type="button"
              onClick={(e) => handleDenyBtnClick(e)}
            >
              Deny
            </button>
          </div>
        ) : (
          <div className="flex flex-row gap-2 justify-end w-1/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}

      {showApproveWorkOrderModal ? (
        <ConfirmModal
          confirmText={`Are you sure you want to approve this work order?`}
          setModalClose={handleApproveWorkOrderModalClose}
          setFormYes={handleApproveWorkOrderSubmit}
        />
      ) : null}
    </>
  );
};

export default WorkOrderWriter;
