import ConfirmModal from "Components/Modal/ConfirmModal";
import DuoConfirmModal from "Components/Modal/DuoConfirmModal";
import React, { useEffect, useState } from "react";
import { useLocation, useNavigate, useParams } from "react-router";

import { GlobalContext, showToast } from "Src/globalContext";
import {
  UpdateEditTypeAPI,
  deleteEditTypeAPI,
  viewEditTypesDetails,
} from "Src/services/editService";
import { removeKeysWhenValueIsNull } from "Utils/utils";

const ViewAdminEditTypePage = () => {
  const { dispatch: globalDispatch } = React.useContext(GlobalContext);
  const [notes, setNotes] = useState("");

  const [viewModelEdit, setViewModelEdit] = React.useState({});

  const [durationOfEditMonth, setDurationOfEditMonth] = React.useState(0);
  const [durationOfEditWeek, setDurationOfEditWeek] = React.useState(0);
  const [durationOfEditDays, setDurationOfEditDay] = React.useState(0);

  const params = useParams();
  const projectID = params?.project_id;
  const isOpen = "view-mode";
  const [showRealDeleteEditModal, setShowRealDeleteEditModal] =
    React.useState(false);
  const [showDeleteEditModal, setShowDeleteEditModal] = React.useState(false);

  const location = useLocation();

  useEffect(() => {
    document.querySelector(".main").scrollTo({ top: 0 });

    window.scrollTo({ top: 0 });
  }, [location.pathname]);

  const handleRealDeleteEditModalClose = () => {
    setShowRealDeleteEditModal(false);
  };

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

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

  const parseAndSetDuration = (durationString) => {
    const [monthsPart, weeksPart, daysPart] = durationString.split(", ");
    const months = parseInt(monthsPart.split(" ")[0]);
    const weeks = parseInt(weeksPart.split(" ")[0]);
    const days = parseInt(daysPart.split(" ")[0]);

    setDurationOfEditMonth(months);
    setDurationOfEditWeek(weeks);
    setDurationOfEditDay(days);
  };

  const navigate = useNavigate();

  const handleDeleteEdit = async (id) => {
    console.log(id);
    // console.log(video);
    await deleteEditTypeAPI(id);
    setShowDeleteEditModal(false);
    navigate("/admin/edits");
    // await getData();
    showToast(globalDispatch, `Special Edit Type Deleted`, 5000);
  };

  const getEditDetails = async () => {
    const res = await viewEditTypesDetails(params.id);

    setNotes(res.model.note_keys);
    parseAndSetDuration(res.model.edit_duration);

    setViewModelEdit(res.model);
  };

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

  console.log(viewModelEdit);

  const updateNote = async () => {
    try {
      const res = await UpdateEditTypeAPI(
        removeKeysWhenValueIsNull({
          note_keys: viewModelEdit.request_range === "Special" ? notes : null,
          edit_duration: `${durationOfEditMonth} months, ${durationOfEditWeek} weeks, ${durationOfEditDays} days`,
          // number_of_lines:
          //   viewModelEdit.request_range === "Special" ? "Special" : null,
        }),
        params?.id
      );

      navigate("/admin/edits");

      showToast(globalDispatch, "Special Edits Updated", 5000, "success");
    } catch (error) {
      showToast(globalDispatch, "Special Edits update failed", 5000, "error");
      throw error;
    }
  };

  return (
    <>
      {" "}
      {showRealDeleteEditModal ? (
        <ConfirmModal
          confirmText={`Are you sure you want to delete this special edit?`}
          setModalClose={handleRealDeleteEditModalClose}
          setFormYes={openSecondDelete}
        />
      ) : null}
      {showDeleteEditModal ? (
        <DuoConfirmModal
          confirmText={`Are you sure you want to delete this special edit? This action cannot be undone.`}
          setModalClose={setShowDeleteEditModal}
          setFormYes={() => {
            handleDeleteEdit(params?.id);
          }}
        />
      ) : null}
      <div className="flex min-h-screen w-full flex-col  rounded-md bg-gray-800 p-5 text-white">
        <div className="flex w-full items-center justify-between">
          <div className="flex items-center gap-1">
            <h6 className="whitespace-normal text-xl font-normal">
              Edit Type:
            </h6>{" "}
            <h6 className="whitespace-normal text-xl font-normal">
              {viewModelEdit?.edit_type}
            </h6>
          </div>
          {viewModelEdit.request_range === "Special" && (
            <div className=" flex w-full items-center justify-end">
              <button
                onClick={() => setShowRealDeleteEditModal(true)}
                className=" flex w-[100px] items-center justify-center gap-1 rounded-md bg-red-800  py-[10px] hover:bg-red-900"
              >
                <span className="  text-[14px] font-medium">Delete Edit</span>
              </button>
            </div>
          )}
        </div>

        <div className="mt-14 flex h-[45px] w-full items-start justify-between gap-5  rounded">
          <div className="whitespace-nowraptext-white flex h-full basis-[20%] ">
            Duration of Edits
          </div>
          <div className="flex w-[70%] gap-4 ">
            <div className="flex flex-col ">
              <h6>Month(s)</h6>
              <input
                className="h-10 w-14 p-[2px] text-center text-black"
                type="number"
                inputMode="numeric"
                onChange={(e) => setDurationOfEditMonth(e.target.value)}
                value={durationOfEditMonth}
                name=""
                required
                id=""
              />
            </div>
            <div className="flex flex-col ">
              <h6>Week(s)</h6>
              <input
                inputMode="numeric"
                onChange={(e) => setDurationOfEditWeek(e.target.value)}
                className="h-10 w-14 p-[2px] text-center text-black"
                type="number"
                value={durationOfEditWeek}
                name=""
                id=""
                required
              />
            </div>
            <div className="flex flex-col ">
              <h6>Day(s)</h6>
              <input
                className="h-10 w-14 p-[2px] text-center text-black"
                type="number"
                inputMode="numeric"
                onChange={(e) => setDurationOfEditDay(e.target.value)}
                value={durationOfEditDays}
                name=""
                required
                id=""
              />
            </div>
          </div>
        </div>

        {viewModelEdit.request_range === "Special" && (
          <div className="mt-14 flex  justify-between gap-4">
            <h6 className="basis-[20%] text-base font-normal">
              Special Edits Note:
            </h6>{" "}
            <div className=" flex w-[70%] flex-col ">
              <textarea
                className="h-[150px]  bg-white text-black"
                name=""
                placeholder="notes"
                id=""
                value={notes}
                onChange={(e) => setNotes(e.target.value)}
              ></textarea>
            </div>
          </div>
        )}

        <div className="mt-20 flex  w-full flex-row-reverse items-center justify-center gap-[80px]">
          <button
            onClick={() => {
              navigate("/admin/edits");
            }}
            className="  flex w-[80px] items-center justify-center gap-1 self-end rounded-md bg-green-800  px-5 py-[10px] hover:bg-green-800/90"
          >
            <span className="  text-[13px] font-medium">Cancel</span>
          </button>
          <button
            onClick={updateNote}
            className="  flex w-[80px] items-center justify-center gap-1 self-end rounded-md bg-green-800  px-5 py-[10px] hover:bg-green-800/90"
          >
            <span className="  text-[13px] font-medium">Update</span>
          </button>
        </div>
      </div>
    </>
  );
};

export default ViewAdminEditTypePage;
