import AdminInstrumentals from "Components/AdminInstrumentals";
import ConfirmModal from "Components/Modal/ConfirmModal";
import EmptyFiles from "Components/PublicWorkOrder/ProducerWorkOrder/EmptyFiles";
import UploadedFiles from "Components/PublicWorkOrder/ProducerWorkOrder/UploadedFiles";
import React from "react";
import { useNavigate } from "react-router-dom";
import { GlobalContext, showToast } from "Src/globalContext";
import { validateUuidv4 } from "Utils/utils";

import { ClipLoader } from "react-spinners";
import { useS3Upload } from "Src/libs/uploads3Hook";
import {
  getProducerWorkOrderPublicDetailsAPI,
  updateProducerWorkOrderAPI,
} from "Src/services/producerWorkOrderService";
import { deleteOneFileAPI } from "Src/services/projectService";
import {
  deleteS3FileAPI,
  uploadFilesDataAPI,
} from "Src/services/workOrderService";

const ProducerWorkOrderPage = () => {
  const { dispatch: globalDispatch, subproject_update } =
    React.useContext(GlobalContext);
  const { uploadS3FilesAPI, progress, error, isUploading } = useS3Upload();
  const navigate = useNavigate();

  const [isLoading, setIsLoading] = React.useState(false);
  const [canUpload, setCanUpload] = React.useState(false);
  const [showSubmitWorkOrderModal, setShowSubmitWorkOrderModal] =
    React.useState(false);

  const [workOrderDetails, setWorkOrderDetails] = React.useState({});
  const [fileType, setFileType] = React.useState("");
  const [employeeId, setEmployeeId] = React.useState(null);

  const [uploadedFiles, setUploadedFiles] = React.useState([]);

  const [adminInstrumentals, setAdminInstrumentals] = React.useState([]);

  const [producerSubmitStatus, setProducerSubmitStatus] = React.useState(false);

  const handleEmployeeType = (employeeType) => {
    if (employeeType === "producer") {
      setEmployeeId(Number(workOrderDetails.producer_id));
    }
  };

  const handleUploadFileType = (fileType) => {
    setFileType(fileType);
  };

  const handleFileUploads = 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.producer_id),
          employee_type: "producer",
          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");
    }
  };

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

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

  const handleSubmitWorkOrder = async () => {
    try {
      const result = await updateProducerWorkOrderAPI({
        id: Number(workOrderDetails.id),
        producer_submit_status: 1,
      });

      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("/producer/")[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 getProducerWorkOrderPublicDetailsAPI({
            uuidv4,
          });

          if (!result.error) {
            setIsLoading(false);
            if (!result.model.producer_submit_status) {
              setCanUpload(true);
              setProducerSubmitStatus(true);
            }

            setWorkOrderDetails(result.model);
            setUploadedFiles(result.model.instrumentals);
            setAdminInstrumentals(result.model.adminInstrumentals);
          } else {
            showToast(globalDispatch, result.message, 5000, "error");
            setIsLoading(false);
            window.location.href = "/member/login";
          }
        })();
      }
    }
    setIsLoading(false);
  }, []);

  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.producer_name}
            </h5>
          </div>

          {adminInstrumentals && adminInstrumentals.length > 0 && (
            <AdminInstrumentals uploadedFiles={adminInstrumentals} />
          )}

          {uploadedFiles.length === 0 && (
            <EmptyFiles
              canUpload={canUpload}
              setEmployeeType={handleEmployeeType}
              setFileUploadType={handleUploadFileType}
              setFormData={handleFileUploads}
            />
          )}
          {uploadedFiles.length > 0 && (
            <UploadedFiles
              canUpload={canUpload}
              uploadedFiles={uploadedFiles}
              setDeleteFileId={handleDeleteFileSubmit}
              setEmployeeType={handleEmployeeType}
              setFileUploadType={handleUploadFileType}
              setFormData={handleFileUploads}
            />
          )}

          {canUpload && (
            <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>
          )}

          {!producerSubmitStatus && (
            <div className="flex flex-col">
              <div className="mb-2 text-center text-xl font-semibold text-white">
                Workorder submitted by the producer.
              </div>
            </div>
          )}
        </div>
      )}

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

      {/* {showSubmitWorkOrderModal ? (
        <ConfirmModal
          confirmText={`Are you sure you want to submit this work order?`}
          setModalClose={handleSubmitWorkOrderModalClose}
          setFormYes={handleSubmitWorkOrder}
        />
      ) : null} */}
    </>
  );
};

export default ProducerWorkOrderPage;
