import ConfirmModal from "Components/Modal/ConfirmModal";
import EngineerSubProjects from "Components/PublicWorkOrder/EngineerWorkOrder/EngineerSubProjects";
import UploadedSessionFiles from "Components/PublicWorkOrder/EngineerWorkOrder/UploadedSessionFiles";
import moment from "moment-timezone";
import React from "react";
import { useNavigate } from "react-router-dom";
import { ClipLoader } from "react-spinners";
import { GlobalContext, showToast } from "Src/globalContext";
import {
  deleteOneFileAPI,
  updateSubProjectDetailsAPI,
} from "Src/services/projectService";
import {
  deleteS3FileAPI,
  getWorkOrderPublicDetailsAPI,
  updateWorkOrderAPI,
} from "Src/services/workOrderService";
import { resetSubProjectsChronology, validateUuidv4 } from "Utils/utils";

const EngineerWorkOrderPage = () => {
  const {
    dispatch: globalDispatch,
    state: { subproject_update },
  } = React.useContext(GlobalContext);

  const navigate = useNavigate();

  const [isLoading, setIsLoading] = React.useState(false);
  const [canUpload, setCanUpload] = React.useState(false);
  const [uploadedSessions, setUploadedSessions] = React.useState([]);
  const [subProjects, setSubProjects] = React.useState([]);
  const [workOrderDetails, setWorkOrderDetails] = React.useState({});

  const [artistSubmitStatus, setArtistSubmitStatus] = React.useState(false);

  const [showSubmitWorkOrderModal, setShowSubmitWorkOrderModal] =
    React.useState(false);

  const handleSubmitWorkOrderModalClose = () => {
    setShowSubmitWorkOrderModal(false);
  };

  const handleSubmitWorkOrderModalOpen = () => {
    setShowSubmitWorkOrderModal(true);
  };

  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 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 handleSubmitWorkOrder = async () => {
    try {
      const result = await updateWorkOrderAPI({
        id: Number(workOrderDetails.id),
        engineer_submit_status: 1,
        status: 5,
        engineer_submission_datetime: moment()
          .tz("America/New_York")
          .format("YYYY-MM-DD HH:mm:ss"),
        is_viewed: 0,
      });

      if (!result.error) {
        showToast(globalDispatch, result.message, 5000);
        handleSubmitWorkOrderModalClose();
        window.location.reload();
      } else {
        showToast(globalDispatch, result.message, 5000, "error");
        return;
      }
    } catch (error) {
      showToast(globalDispatch, error.message, 5000, "error");
    }
  };

  React.useEffect(() => {
    const url = new URL(window.location.href);
    const uuidv4 = url.pathname.split("/engineer/")[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 () {
          const result = await getWorkOrderPublicDetailsAPI({
            uuidv4,
            employee_type: "engineer",
          });
          if (!result.error) {
            setIsLoading(false);
            if (!result.model.engineer_submit_status) {
              setCanUpload(true);
            }

            if (result.model.artist_submit_status) {
              setArtistSubmitStatus(true);
            }

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

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

  return (
    <>
      {isLoading ? (
        <div className="flex h-screen items-center justify-center">
          <ClipLoader color="#fff" size={30} />
        </div>
      ) : (
        <div className="my-8 flex flex-col items-center justify-center gap-4">
          <div className="flex w-full max-w-5xl flex-row flex-wrap justify-between ">
            <h5 className="text-md mb-2 items-center text-2xl font-semibold text-white">
              Work Order - {workOrderDetails.workorder_code}:{" "}
              {workOrderDetails.writer ? workOrderDetails.writer.name : ""} for{" "}
              {workOrderDetails.artist ? workOrderDetails.artist.name : ""}
            </h5>
          </div>

          {/* Session files */}
          <UploadedSessionFiles
            code={workOrderDetails.workorder_code}
            canUpload={canUpload}
            uploadedFiles={uploadedSessions}
            setDeleteFileId={handleDeleteFileSubmit}
          />

          {/* master files */}
          <div className="mt-4 flex w-full max-w-5xl flex-row flex-wrap justify-between">
            <h5 className="text-md items-center font-semibold text-white">
              Master Files
            </h5>
          </div>

          {/* subprojects */}
          <EngineerSubProjects
            isPublic={true}
            canUpload={canUpload}
            subProjects={subProjects}
            workOrderDetails={workOrderDetails}
            setDeleteFileId={handleDeleteFileSubmit}
            setSubProjectDetails={handleUpdateSubProjectDetails}
          />

          {canUpload && artistSubmitStatus && (
            <div className="flex w-full max-w-5xl flex-row flex-wrap justify-end">
              <button
                className="w-[220px] rounded bg-primary px-6 py-4 font-bold text-white hover:bg-primary"
                type="button"
                onClick={(e) => {
                  e.preventDefault();
                  handleSubmitWorkOrderModalOpen();
                }}
              >
                Submit
              </button>
            </div>
          )}
          {!artistSubmitStatus && (
            <div className="flex flex-col">
              <div className="mb-2 text-center text-xl font-semibold text-white">
                You do not have permission to upload because workorder has not
                yet submitted by the artist.
              </div>
            </div>
          )}
          {!canUpload && (
            <div className="flex flex-col">
              <div className="mb-2 text-center text-xl font-semibold text-white">
                Workorder Submitted by Engineer
              </div>
            </div>
          )}
        </div>
      )}

      {showSubmitWorkOrderModal ? (
        <ConfirmModal
          confirmText={
            uploadedSessions.length <= 0 ||
            masters === 0 ||
            Lyrics.length > 0 ||
            songDetails.length > 0 ? (
              <div>
                <p>The following information is missing:</p>
                <ul className="list-disc">
                  {uploadedSessions.length === 0 && <li>Session files</li>}
                  {masters === 0 && <li>Master files</li>}
                  {/* {Lyrics.length > 0 && <li>Lyrics</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 EngineerWorkOrderPage;
