import ConfirmModal from "Components/Modal/ConfirmModal";
import DuoConfirmModal from "Components/Modal/DuoConfirmModal";
import Spinner from "Components/Spinner";
import moment from "moment";
import React, { useEffect, useState } from "react";
import { useNavigate } from "react-router";
import { GlobalContext, showToast } from "Src/globalContext";
import {
  deleteEightCountAPI,
  deleteMediaAPI,
} from "Src/services/clientProjectDetailsService";
import {
  CreateEditAPI,
  UpdateEditAPI,
  getAllEditTypesListAPI,
} from "Src/services/editService";
import { updateProjectAPI } from "Src/services/projectService";
import ClientEightCountTab from "./ClientViewProjectDetails/ClientEightCountTab";
import VideoSection from "./ClientViewProjectDetails/VideoSection";

const EditView = ({
  SameTeamNameEdit = null,
  isOpen,
  setReviseEdit,
  setIsOpen,
  selectedEditType,
  setConfirmationPage,
  submittedIdeas,
  surveyLink,
  viewModel,
  loader,
  projectID,
  selectedTeam,
  producerName,
  producer_id,
  setEditData,
  setSelectedTeam,
  reviseEdit,
}) => {
  console.log(viewModel);
  const [notes, setNotes] = useState("");
  const [loading, setLoading] = useState(false);
  const { dispatch: globalDispatch } = React.useContext(GlobalContext);
  const [showRealSubmitEditModal, setShowRealSubmitEditModal] =
    React.useState(false);
  const [showSubmitEditModal, setShowSubmitEditModal] = React.useState(false);
  const [edit_ID, set_Edit_ID] = useState(0);
  const [video_ids, setVideo_ids] = useState([]);
  const [numberOfEdited, setNumberOfEdited] = useState(0);
  const [editTypeLists, setEditTypeLists] = useState([]);
  const [editTypeListsSpecial, setEditTypeListsSpecial] = useState([]);
  const [triggerSave, setTriggerSave] = useState("");
  const editIdRef = React.useRef(edit_ID);

  const [uploaded_eight_count, setUploaded_eight_count] = useState([]);
  const isOpenRef = React.useRef(!isNaN(isOpen) ? 1 : "");
  console.log(viewModel);
  React.useEffect(() => {
    editIdRef.current = edit_ID;
  }, [edit_ID]);
  const [hasSubmitted, setHasSubmitted] = useState(false);

  console.log(edit_ID);
  console.log(SameTeamNameEdit);

  useEffect(() => {
    !isNaN(isOpen) &&
      SameTeamNameEdit?.video_ids &&
      setVideo_ids(JSON.parse(SameTeamNameEdit?.video_ids || ""));

    !isNaN(isOpen) && setNotes(SameTeamNameEdit?.producer_notes);
  }, []);

  console.log(isOpen);

  useEffect(() => {
    if (!isNaN(isOpen)) {
      set_Edit_ID(isOpen);
    }
  }, [isOpen]);

  const getTypeList = async () => {
    try {
      const res = await getAllEditTypesListAPI({
        user_id: producer_id,
      });
      const newList = res.list.filter(
        (elem) => elem.request_range !== "Special"
      );
      const newListSpe = res.list.filter(
        (elem) => elem.request_range === "Special"
      );
      setEditTypeListsSpecial(newListSpe);
      setEditTypeLists(newList);
    } catch (error) {}
  };

  useEffect(() => {
    getTypeList();
  }, []);

  function calculateDueDate(editDuration) {
    const [monthsPart, weeksPart, daysPart] = editDuration.split(", ");
    const months = parseInt(monthsPart.split(" ")[0]);
    const weeks = parseInt(weeksPart.split(" ")[0]);
    const days = parseInt(daysPart.split(" ")[0]);

    const createDate = new Date();

    // Add months, weeks, and days to the create date
    const dueDate = new Date(createDate);
    dueDate.setMonth(dueDate.getMonth() + months);
    dueDate.setDate(dueDate.getDate() + weeks * 7 + days);

    // Format the due date as dd-mm-yy
    const day = String(dueDate.getDate()).padStart(2, "0");
    const month = String(dueDate.getMonth() + 1).padStart(2, "0"); // Months are 0-based
    const year = String(dueDate.getFullYear());

    return `${year}-${month}-${day}`;
  }

  const handleRealSubmitEditModalClose = () => {
    setShowRealSubmitEditModal(false);
  };

  const openSecondDelete = () => {
    setShowRealSubmitEditModal(false);

    setTimeout(() => {
      setShowSubmitEditModal(true);
    }, 500);
  };

  function getEntityType(number, data) {
    let matchingEntity = null;
    let highestEntity = null;
    let highestValue = -Infinity;

    data.forEach((entity) => {
      const numberOfLines = entity.number_of_lines;

      if (numberOfLines.includes("Special")) {
        // Skip special cases for now or handle accordingly
        return;
      }

      const parts = numberOfLines.split(" ");
      if (parts.length === 3) {
        const bound = parseInt(parts[0]);
        const comparison = parts[2];

        if (comparison === "below" && number <= bound) {
          matchingEntity = entity;
        } else if (comparison === "up" && number >= bound) {
          matchingEntity = entity;
        }

        // Track the highest range entity
        if (comparison === "up" && bound > highestValue) {
          highestValue = bound;
          highestEntity = entity;
        }
      }
    });

    // If number exceeds all defined ranges, return the highest range entity
    if (!matchingEntity && highestEntity) {
      matchingEntity = highestEntity;
    }

    return matchingEntity;
  }

  console.log(calculateDueDate("0 months, 5 weeks, 0 days"));

  const navigate = useNavigate();

  const edit = editTypeLists.find((elem) => elem.id == selectedEditType);
  const editSpecial = editTypeListsSpecial.find(
    (elem) => elem.id == selectedEditType
  );

  console.log(edit_ID, numberOfEdited);

  console.log(notes);
  const onUpdate = async () => {
    try {
      let edit_type_default = {};
      let dueDate = null;

      // Check if selectedEditType is not provided
      if (!selectedEditType) {
        console.log("Edit type lists:", editTypeLists);
        edit_type_default = getEntityType(
          SameTeamNameEdit?.number_of_lines
            ? numberOfEdited + parseInt(SameTeamNameEdit?.number_of_lines)
            : numberOfEdited,
          editTypeLists
        );
        console.log("Default edit type:", edit_type_default);
        dueDate = calculateDueDate(edit_type_default?.edit_duration);
      } else {
        const edit = editTypeListsSpecial.find(
          (elem) => elem.id == selectedEditType
        );
        edit_type_default = {
          id: "",
          edit_type: "Special",
          edit_type_name: edit?.edit_type,
        };
        console.log(selectedEditType);

        console.log(edit);
        dueDate = calculateDueDate(edit?.edit_duration);
      }
      setLoading(true);

      const payload = {
        producer_notes: notes,
        edit_type: edit_type_default?.id,

        request_date: moment(new Date()).format("YYYY-MM-DD"),
        due_date: dueDate,
        edit_policy: "",
        eight_count: edit_ID,
        special_edit: selectedEditType ? 1 : 0,
        special_type: selectedEditType ? selectedEditType : "",
        edit_type_name: selectedEditType
          ? edit_type_default?.edit_type_name
          : edit_type_default?.edit_type,
        video_ids: JSON.stringify(video_ids),
        edit_status: 2,
        number_of_lines: SameTeamNameEdit?.number_of_lines
          ? String(numberOfEdited + parseInt(SameTeamNameEdit?.number_of_lines))
          : String(numberOfEdited),
      };
      const res = await UpdateEditAPI(payload, SameTeamNameEdit?.id);

      setEditData({
        program_name: selectedTeam.program,
        team_name: selectedTeam.label,
        producer: producerName,
        edit_type: selectedEditType
          ? editSpecial.edit_type
          : edit_type_default?.edit_type,
        request_date: moment(new Date()).format("YYYY-MM-DD"),
        due_date: dueDate,
      });

      if (!res?.error) {
        showToast(globalDispatch, `Edit Revised Sucessfully`, 5000);
        await updateProjectAPI({
          id: projectID.toString(),
          discount: 0,
          payment_status: 4,
        });
        setHasSubmitted(true);
        setLoading(false);
        setSelectedTeam(null);
        setConfirmationPage(true);
        isOpenRef.current = 1;
        setIsOpen(false);
      } else {
        showToast(globalDispatch, `Edit Creation Failed`, 5000, "error");
      }
    } catch (error) {
      showToast(globalDispatch, `Edit Revision Failed`, 5000, "error");
      console.log(error);
      setLoading(false);
      throw error;
    } finally {
      setLoading(false);
      setReviseEdit(false);
    }
  };
  console.log(isOpen);
  console.log(edit_ID);
  const onSubmit = async () => {
    setTriggerSave(!triggerSave);
    try {
      let edit_type_default = {};
      let dueDate = null;

      // Check if selectedEditType is not provided
      if (!selectedEditType) {
        console.log("Edit type lists:", editTypeLists);
        edit_type_default = getEntityType(numberOfEdited, editTypeLists);
        console.log("Default edit type:", edit_type_default);
        dueDate = calculateDueDate(edit_type_default?.edit_duration);
      } else {
        const edit = editTypeListsSpecial.find(
          (elem) => elem.id == selectedEditType
        );
        edit_type_default = {
          id: "",
          edit_type: "Special",
          edit_type_name: edit?.edit_type,
        };
        console.log(selectedEditType);

        console.log(edit);
        dueDate = calculateDueDate(edit?.edit_duration);
      }
      setLoading(true);
      console.log(edit_ID);
      const payload = {
        program_name: selectedTeam.program,
        team_name: selectedTeam.label,
        producer: producerName,
        user_id: localStorage.getItem("user"),
        producer_id: producer_id,
        producer_notes: notes,
        edit_type: edit_type_default?.id,
        completed_date: "",
        request_date: moment(new Date()).format("YYYY-MM-DD"),
        due_date: dueDate,

        edit_policy: "",
        eight_count: edit_ID,
        special_edit: selectedEditType ? 1 : 0,
        special_type: selectedEditType ? selectedEditType : "",
        edit_type_name: selectedEditType
          ? edit_type_default?.edit_type_name
          : edit_type_default?.edit_type,
        video_ids: JSON.stringify(video_ids),
        edit_status: 2,
        number_of_lines: numberOfEdited,
        project_id: projectID,
        music_ids: JSON.stringify([]),
      };
      const res = await CreateEditAPI(payload);
      setEditData({
        program_name: selectedTeam.program,
        team_name: selectedTeam.label,
        producer: producerName,
        edit_type: selectedEditType
          ? editSpecial.edit_type
          : edit_type_default?.edit_type,
        request_date: moment(new Date()).format("YYYY-MM-DD"),
        due_date: dueDate,
        music_ids: JSON.stringify([]),
      });

      if (!res?.error) {
        showToast(globalDispatch, `Edit Created Sucessfully`, 5000);
        await updateProjectAPI({
          id: projectID,
          discount: 0,
          payment_status: 4,
        });
        setHasSubmitted(true);
        setLoading(false);
        setSelectedTeam(null);
        setConfirmationPage(true);
        isOpenRef.current = 1;
        setIsOpen(false);
        setNotes("");
        setReviseEdit(false);
      } else {
        showToast(globalDispatch, `Edit Creation Failed`, 5000, "error");
      }
    } catch (error) {
      showToast(globalDispatch, `Edit Creation Failed`, 5000, "error");
      console.log(error);
      setLoading(false);
      throw error;
    } finally {
      setLoading(false);
      setReviseEdit(false);
    }
  };

  console.log(isOpen);

  const videoIdsRef = React.useRef(video_ids);

  useEffect(() => {
    videoIdsRef.current = video_ids;
  }, [video_ids]);

  useEffect(() => {
    const handleBeforeUnload = (event) => {
      if (!hasSubmitted) {
        event.preventDefault();
        event.returnValue = "";
        return "";
      }

      // Keep your existing eight count deletion logic
      (async function () {
        try {
          if (isOpenRef?.current === "" || Number.isNaN(isOpenRef?.current)) {
            console.log(editIdRef?.current);
            await deleteEightCountAPI(editIdRef?.current);
            videoIdsRef.current.forEach(async (elem) => {
              await deleteMediaAPI(elem);
            });
          }
        } catch (error) {
          console.log(error);
        }
      })();
    };

    window.addEventListener("beforeunload", handleBeforeUnload);
    return () => window.removeEventListener("beforeunload", handleBeforeUnload);
  }, [hasSubmitted]);

  React.useEffect(() => {
    return () => {
      (async function () {
        try {
          if (isOpenRef?.current === "" || Number.isNaN(isOpenRef?.current)) {
            console.log(editIdRef?.current);
            await deleteEightCountAPI(editIdRef?.current);
            videoIdsRef.current.forEach(async (elem) => {
              await deleteMediaAPI(elem);
            });
          }
        } catch (error) {
          console.log(error);
        }
      })();
    };
  }, []);

  console.log(video_ids, "video idsss");
  console.log(isOpen);
  console.log(showSubmitEditModal, "sjjs");

  if (loader || loading) {
    return <Spinner />;
  }
  return (
    <>
      {" "}
      {showRealSubmitEditModal ? (
        <ConfirmModal
          confirmText={`Are you sure you want to Submit this edit?`}
          setModalClose={handleRealSubmitEditModalClose}
          setFormYes={openSecondDelete}
        />
      ) : null}
      {showSubmitEditModal ? (
        <DuoConfirmModal
          confirmText={`Are you sure you want to Submit this edit? This action cannot be undone.`}
          setModalClose={setShowSubmitEditModal}
          setFormYes={() => {
            if (!isNaN(isOpen)) {
              onUpdate();
            } else {
              onSubmit();
            }
          }}
        />
      ) : null}
      <div className="relative flex min-h-screen w-full flex-col rounded-md bg-boxdark p-5 text-white">
        {loader || loading ? null : (
          <button
            style={{
              textOrientation: "upright",
              writingMode: "vertical-lr",
              WebkitWritingMode: "vertical-lr",
              msWritingMode: "vertical-lr",
            }}
            className="fixed right-[30px] top-[50%] z-[9] flex w-[50px] items-center justify-center gap-1 rounded-md border  border-black/70 bg-primary py-[10px] text-lg font-semibold uppercase tracking-[-1px] shadow-md "
            onClick={() => {
              setShowRealSubmitEditModal(true);
            }}
          >
            Submit Edit
          </button>
        )}
        <div className="space-y-6">
          {/* Header Section */}
          <div className="border-b border-strokedark pb-3 dark:border-strokedark">
            <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
              <div>
                <div className="flex items-center gap-1">
                  <h3 className="text-xl font-medium text-white">
                    Edit Request for
                  </h3>
                  <p className="text-xl font-medium text-white">
                    {selectedTeam?.program || "N/A"}
                  </p>
                  <span>-</span>
                  <span className="cursor-pointer text-xl">
                    {selectedTeam?.team_name || "N/A"}
                  </span>
                </div>
                <div className="flex items-center gap-2">
                  <span>Producer Name</span>
                  <span>{producerName}</span>
                </div>
              </div>
            </div>
          </div>

          {/* Notes Section */}
          <div className="mb-4">
            <label className="mb-2.5 block text-sm font-medium text-white dark:text-white">
              Notes for Producer
            </label>
            <textarea
              className="dark:border-form-stroke w-full rounded border-[1.5px] border-stroke bg-form-input bg-transparent px-5 py-3 font-medium outline-none transition focus:border-primary active:border-primary disabled:cursor-default disabled:bg-whiter dark:bg-form-input dark:focus:border-primary"
              rows="4"
              placeholder="Notes for producer"
              value={notes}
              onChange={(e) => setNotes(e.target.value)}
            />
          </div>
        </div>
        <div className="mt-14 w-full bg-gray-700 p-5">
          <div className="custom-overflow h-auto max-h-[300px] overflow-y-auto">
            <VideoSection
              video_ids={video_ids}
              setVideo_ids={setVideo_ids}
              viewModel={viewModel}
              projectID={projectID}
            />
          </div>

          <div className="mt-10">
            <ClientEightCountTab
              triggerSave={triggerSave}
              numberOfEdited={numberOfEdited}
              setNumberOfEdited={setNumberOfEdited}
              action={isOpen}
              edit_eight_count_id={isOpen}
              edit_ID={edit_ID}
              setUploaded_eight_count={setUploaded_eight_count}
              set_Edit_ID={set_Edit_ID}
              surveyLink={surveyLink}
              viewModel={viewModel}
              projectID={projectID}
              submittedIdeas={submittedIdeas}
              reviseEdit={reviseEdit}
            />
          </div>
        </div>
        <div className="mt-8 flex w-full items-center justify-center">
          <button
            className="flex w-[200px] items-center justify-center gap-1 rounded-md border border-black/70 bg-primary py-[15px]"
            onClick={() => {
              setShowRealSubmitEditModal(true);
            }}
          >
            <span className="text-[14px] font-medium">Submit</span>
          </button>
        </div>
      </div>
    </>
  );
};

export default EditView;
