import React from "react";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import moment from "moment";
import { GlobalContext, showToast } from "Src/globalContext";
import { sendEmailAPIV3 } from "Src/services/emailService";
import { uploadFilesDataAPI } from "Src/services/workOrderService";
import UploadedSessions from "Components/PublicWorkOrder/ArtistWorkOrder/UploadedSessions";
import EmptySessions from "Components/PublicWorkOrder/ArtistWorkOrder/EmptySessions";
import EngineerSubProjects from "Components/WorkOrder/ArtistEngineer/EngineerSubProjects";
import ConfirmModal from "Components/Modal/ConfirmModal";
import {
  copyLinkToClipboard,
  dateTimeToFormattedString,
  resetSubProjectsChronology,
} from "Utils/utils";
import EngineerSubProject from "../Engineer/EngineerSubProject";
import { useS3Upload } from "Src/libs/uploads3Hook";

const WorkOrderArtistEngineer = ({
  sessions,
  subProjects,
  workOrderDetails,
  setDeleteFileId,
  setCompleteWorkOrder,
  setLyrics,
}) => {
  const {
    dispatch: globalDispatch,
    state: { subproject_update },
  } = React.useContext(GlobalContext);
  const { uploadS3FilesAPI, progress, error, isUploading } = useS3Upload();
  const [showCompleteWorkOrderModal, setShowCompleteWorkOrderModal] =
    React.useState(false);
  const [showCompleteWorkOrderModal2, setShowCompleteWorkOrderModal2] =
    React.useState(false);

  const [employeeId, setEmployeeId] = React.useState(null);
  const [fileType, setFileType] = React.useState("");
  const [employeeType, setEmployeeType] = React.useState("");

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

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

  const handleCompleteWorkOrderBtnSubmit2 = async () => {
    setCompleteWorkOrder(true);
    setShowCompleteWorkOrderModal2(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/Engineer 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/engineer-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 and 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}.<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 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 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"
          );
        }
      } else {
        showToast(globalDispatch, result.message, 5000, "error");
      }
    } catch (error) {
      showToast(globalDispatch, error.message, 5000, "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 handleCompleteWorkOrderModalClose2 = () => {
    setShowCompleteWorkOrderModal2(false);
  };

  return (
    <>
      {window.location.pathname.includes("edit-work-order") ? null : (
        <>
          <div className="flex w-full flex-row flex-wrap justify-between">
            <h5 className="text-md mb-2 items-center font-semibold text-white">
              Session Files
            </h5>
          </div>

          <div className="mb-2 block w-full rounded-md border border-gray-500 bg-gray-800 p-5 shadow">
            <div className="flex flex-col">
              <div className="mb-4 font-semibold text-white">
                Uploaded Files
              </div>

              {sessions && sessions.length > 0 ? (
                <UploadedSessions
                  uploadedFiles={sessions}
                  uploadedFilesProgressData={{ progress, error, isUploading }}
                  setDeleteFileId={setDeleteFileId}
                  setEmployeeType={handleEmployeeType}
                  setFileUploadType={handleUploadFileType}
                  setFormData={handleSessionUploads}
                />
              ) : (
                <EmptySessions
                  uploadedFilesProgressData={{ progress, error, isUploading }}
                  setEmployeeType={handleEmployeeType}
                  setFileUploadType={handleUploadFileType}
                  setFormData={handleSessionUploads}
                />
              )}
            </div>
          </div>
        </>
      )}

      <div className="flex flex-col gap-3">
        {subProjects &&
          subProjects.length > 0 &&
          subProjects.map((subProject, index) => {
            return (
              <EngineerSubProject
                key={index}
                workOrderDetails={workOrderDetails}
                subProject={subProject}
                uploadedDemoFiles={subProject.demos}
                uploadedMasterFiles={subProject.masters}
                setLyrics={setLyrics}
                setDeleteFileId={setDeleteFileId}
              />
            );
          })}
      </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/Engineer
          </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/engineer-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 complete this work order?`}
          setModalClose={handleCompleteWorkOrderModalClose}
          setFormYes={handleCompleteWorkOrderBtnSubmit}
        />
      ) : null}
    </>
  );
};

export default WorkOrderArtistEngineer;
