import ConfirmModal from "Components/Modal/ConfirmModal";
import SubProjects from "Components/PublicWorkOrder/WriterArtistEngineerWorkOrder/SubProjects";
import EmptySessions from "Components/PublicWorkOrder/WriterArtistWorkOrder/EmptySessions";
import UploadedSessions from "Components/PublicWorkOrder/WriterArtistWorkOrder/UploadedSessions";
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 { useS3Upload } from "Src/libs/uploads3Hook";
import {
  deleteOneFileAPI,
  updateSubProjectDetailsAPI,
} from "Src/services/projectService";
import {
  deleteS3FileAPI,
  getWorkOrderPublicDetailsAPI,
  updateLyricsPublicAPI,
  updateWorkOrderAPI,
  uploadFilesDataAPI,
} from "Src/services/workOrderService";
import { resetSubProjectsChronology, validateUuidv4 } from "Utils/utils";

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

  const { subProjectLyrics, songSubProjects } = state;

  console.log(subProjectLyrics);

  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 [showSubmitWorkOrderModal, setShowSubmitWorkOrderModal] =
    React.useState(false);

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

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

  const handleUpdateLyrics = async (payload) => {
    try {
      const result = await updateLyricsPublicAPI(payload);
      if (!result.error) {
        showToast(globalDispatch, "Lyrics 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 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 handleSubmitWorkOrder = 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,
        is_viewed: 0,
        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");
        handleSubmitWorkOrderModalClose();
        window.location.reload();
        globalDispatch({
          type: "SET_SUBPROJECT_UPDATE",
          payload: !subproject_update,
        });
      } else {
        showToast(globalDispatch, result.message, 5000, "error");
        return;
      }
    } 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 handleSaveAll = async () => {
    try {
      await handleSaveAllLyrics();
      await handleSaveAllSubProjectDetails();
      globalDispatch({
        type: "SET_SUBPROJECT_UPDATE",
        payload: !subproject_update,
      });
    } catch (error) {
      showToast(globalDispatch, error.message, 5000, "error");
    }
  };

  const handleSaveAllLyrics = async () => {
    try {
      // subProjectLyrics
      // [{
      //    subproject_id: subProjectId,
      //    lyrics: e.target.value,
      // }]

      // if (subProjectLyrics.length === 0) {
      //   showToast(
      //     globalDispatch,
      //     "No changes found to update for save all lyrics",
      //     5000,
      //     "warning"
      //   );
      //   setIsLoading(false);
      //   return;
      // }

      const updateLyricsPromises = subProjectLyrics.map((row) => {
        return updateLyricsPublicAPI({
          subproject_id: row.subproject_id,
          lyrics: row.lyrics,
        });
      });

      const results = await Promise.all(updateLyricsPromises);

      // Check if all updates were successful
      const allSuccessful = results.every((result) => !result.error);

      if (allSuccessful) {
        showToast(globalDispatch, "Lyrics updated successfully", 5000);
        // window.location.reload();
        globalDispatch({
          type: "SET_SUBPROJECT_UPDATE",
          payload: !subproject_update,
        });
      } else {
        showToast(globalDispatch, "Error updating lyrics", 5000, "error");
      }
      setIsLoading(false);
    } catch (error) {
      showToast(globalDispatch, error.message, 5000, "error");
    }
  };

  const handleSaveAllSubProjectDetails = async () => {
    try {
      // songSubProjects
      // [{
      //    subproject_id: 123,
      //    type_name: 'Hola Amigo',
      //    bpm: '125',
      //    song_key: 'C',
      //    is_song: 1,
      // }]

      // if (songSubProjects.length === 0) {
      //   showToast(
      //     globalDispatch,
      //     "No changes found to update the all sub project details",
      //     5000,
      //     "warning"
      //   );
      //   setIsLoading(false);
      //   return;
      // }

      const updateSubProjectDetailsPromises = songSubProjects.map((row) => {
        return updateSubProjectDetailsAPI({
          subproject_id: row.subproject_id,
          type_name: row.type_name,
          bpm: row.bpm,
          song_key: row.song_key,
          is_song: row.is_song,
        });
      });

      const results = await Promise.all(updateSubProjectDetailsPromises);

      // Check if all updates were successful
      const allSuccessful = results.every((result) => !result.error);

      if (allSuccessful) {
        showToast(
          globalDispatch,
          "All Sub-project details updated successfully",
          5000
        );
        // window.location.reload();
      } else {
        showToast(
          globalDispatch,
          "Error updating all sub-project details",
          5000,
          "error"
        );
      }
      setIsLoading(false);
    } catch (error) {
      showToast(globalDispatch, error.message, 5000, "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);
          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");
    }
  };

  React.useEffect(() => {
    const url = new URL(window.location.href);
    const uuidv4 = url.pathname.split("/writer-artist-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: "writer",
          });
          if (!result.error) {
            setIsLoading(false);
            console.log(
              !result.model.writer_submit_status,
              result.model.auto_approve === 1
            );
            if (
              !result.model.writer_submit_status &&
              result.model.auto_approve === 1
            ) {
              if (
                result.model.writer_id === result.model.artist_id &&
                result.model.writer_id === result.model.engineer_id
              ) {
                setCanUpload(true);
              }
            }

            setWorkOrderDetails(result.model);
            // setSubProjects(result.model.sub_projects);
            setSubProjects(
              resetSubProjectsChronology(result.model.sub_projects)
            );
            setUploadedSessions(result.model.sessions);
            setIsLoading(false);
          } 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) => {
    console.log(
      subproject.bpm,
      "k",
      subproject.song_key,
      "k",
      subproject.song_title
    );
    return (
      subproject.is_song &&
      (!subproject.bpm || !subproject.song_key || !subproject.type_name)
    );
  });

  console.log(songDetails, subProjects);

  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?.name} for{" "}
              {workOrderDetails.artist ? workOrderDetails.artist.name : ""}
            </h5>
          </div>
          {/* session files */}
          {console.log(uploadedSessions)}
          <div className="mb-2 block h-[320px] w-full max-w-5xl rounded bg-boxdark p-5 shadow">
            {uploadedSessions.length > 0 ? (
              <UploadedSessions
                uploadedFilesProgressData={{ progress, error, isUploading }}
                canUpload={canUpload}
                uploadedFiles={uploadedSessions}
                setDeleteFileId={handleDeleteFileSubmit}
                setFormData={handleSessionUploads}
              />
            ) : (
              <EmptySessions
                uploadedFilesProgressData={{ progress, error, isUploading }}
                canUpload={canUpload}
                setFormData={handleSessionUploads}
              />
            )}
          </div>
          <SubProjects
            canUpload={canUpload}
            subProjects={subProjects}
            workOrderDetails={workOrderDetails}
            setLyrics={handleUpdateLyrics}
            setDeleteFileId={handleDeleteFileSubmit}
            setSubProjectDetails={handleUpdateSubProjectDetails}
          />
          {canUpload && (
            <div className="flex w-full max-w-5xl flex-row flex-wrap justify-between">
              <button
                className="rounded bg-primary px-6 py-2 font-bold text-white hover:bg-primary/90"
                type="button"
                onClick={(e) => {
                  e.preventDefault();
                  handleSaveAll();
                }}
              >
                Save All
              </button>
              <button
                className="w-[220px] rounded bg-primary px-6 py-4 font-bold text-white hover:bg-primary"
                type="button"
                onClick={async (e) => {
                  e.preventDefault();
                  if (subProjectLyrics.length > 0) {
                    await handleSaveAllLyrics();
                    console.log("pop");
                    globalDispatch({
                      type: "SET_SUBPROJECT_UPDATE",
                      payload: !subproject_update,
                    });
                    console.log("poeooe");
                  }
                  if (songSubProjects.length > 0) {
                    await handleSaveAllSubProjectDetails();
                    globalDispatch({
                      type: "SET_SUBPROJECT_UPDATE",
                      payload: !subproject_update,
                    });
                  }
                  handleSubmitWorkOrderModalOpen();
                }}
              >
                Submit
              </button>
            </div>
          )}
          {!canUpload && (
            <div className="flex flex-col">
              <div className="mb-2 text-center text-xl font-semibold text-white">
                Workorder Submitted by Writer
              </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>}
                  {songDetails.length > 0 && <li>Song Details Field</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 WriterArtistEngineerWorkOrderPage;
