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 ViewMemberEditTypePage = () => {
  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 [showRealDeleteEditModal, setShowRealDeleteEditModal] =
    React.useState(false);
  const [showDeleteEditModal, setShowDeleteEditModal] = React.useState(false);

  const location = useLocation();

  useEffect(() => {
    document
      .getElementById("mainContainer")
      .scrollTo({ top: 0, behavior: "smooth" });

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

  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 handleRealDeleteEditModalClose = () => {
    setShowRealDeleteEditModal(false);
  };

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

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

  const navigate = useNavigate();

  const handleDeleteEdit = async (id) => {
    console.log(id);
    // console.log(video);
    await deleteEditTypeAPI(id);
    setShowDeleteEditModal(false);
    navigate("/member/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("/member/edits");
      showToast(globalDispatch, "Edit Updated", 5000, "success");
    } catch (error) {
      showToast(globalDispatch, "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}
        />
      )}
      {showDeleteEditModal && (
        <DuoConfirmModal
          confirmText={`Are you sure you want to delete this special edit? This action cannot be undone.`}
          setModalClose={setShowDeleteEditModal}
          setFormYes={() => handleDeleteEdit(params?.id)}
        />
      )}

      <div className="max-w-screen h-full p-4 md:p-4 lg:p-6 xl:p-8">
        <div className="shadow-default rounded border border-strokedark bg-boxdark dark:border-strokedark dark:bg-boxdark">
          {/* Header Section */}
          <div className="sm:px-6.5 border-b border-strokedark px-4 py-4 dark:border-strokedark">
            <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
              <div className="flex items-center gap-2">
                <h3 className="text-xl font-medium text-white">Edit Type:</h3>
                <span className="text-xl font-medium text-white">
                  {viewModelEdit?.edit_type}
                </span>
              </div>
              <div className="flex flex-wrap items-center gap-3">
                {viewModelEdit.request_range === "Special" && (
                  <button
                    onClick={() => setShowRealDeleteEditModal(true)}
                    className="inline-flex items-center justify-center rounded-md bg-danger px-6 py-2.5 text-center font-medium text-white hover:bg-opacity-90"
                  >
                    Delete Edit
                  </button>
                )}
              </div>
            </div>
          </div>

          {/* Content Section */}
          <div className="p-4 md:p-6 2xl:p-10">
            <div className="space-y-6">
              {/* Duration Section */}
              <div className="border-b border-strokedark pb-6 dark:border-strokedark">
                <span className="text-sm text-gray-400">Duration of Edits</span>
                <div className="mt-3 flex gap-4">
                  <div className="flex flex-col gap-2">
                    <label className="text-sm text-gray-400">Month(s)</label>
                    <input
                      className="w-20 rounded border border-strokedark bg-boxdark px-3 py-2 text-white focus:border-primary"
                      type="number"
                      inputMode="numeric"
                      onChange={(e) => setDurationOfEditMonth(e.target.value)}
                      value={durationOfEditMonth}
                      required
                    />
                  </div>
                  <div className="flex flex-col gap-2">
                    <label className="text-sm text-gray-400">Week(s)</label>
                    <input
                      className="w-20 rounded border border-strokedark bg-boxdark px-3 py-2 text-white focus:border-primary"
                      type="number"
                      inputMode="numeric"
                      onChange={(e) => setDurationOfEditWeek(e.target.value)}
                      value={durationOfEditWeek}
                      required
                    />
                  </div>
                  <div className="flex flex-col gap-2">
                    <label className="text-sm text-gray-400">Day(s)</label>
                    <input
                      className="w-20 rounded border border-strokedark bg-boxdark px-3 py-2 text-white focus:border-primary"
                      type="number"
                      inputMode="numeric"
                      onChange={(e) => setDurationOfEditDay(e.target.value)}
                      value={durationOfEditDays}
                      required
                    />
                  </div>
                </div>
              </div>

              {/* Special Edits Note Section */}
              {viewModelEdit.request_range === "Special" && (
                <div className="border-b border-strokedark pb-6 dark:border-strokedark">
                  <span className="text-sm text-gray-400">
                    Special Edits Note
                  </span>
                  <div className="mt-3">
                    <textarea
                      className="w-full rounded border border-strokedark bg-boxdark p-3 text-white placeholder-gray-400 focus:border-primary"
                      rows="4"
                      placeholder="Enter notes"
                      value={notes}
                      onChange={(e) => setNotes(e.target.value)}
                    ></textarea>
                  </div>
                </div>
              )}

              {/* Action Buttons */}
              <div className="flex justify-center gap-4">
                <button
                  onClick={updateNote}
                  className="inline-flex items-center justify-center rounded-md bg-primary px-6 py-2.5 text-center font-medium text-white hover:bg-opacity-90"
                >
                  Update
                </button>
                <button
                  onClick={() => navigate("/member/edits")}
                  className="inline-flex items-center justify-center rounded-md border border-strokedark bg-meta-4 px-6 py-2.5 text-center font-medium text-white hover:bg-opacity-90"
                >
                  Cancel
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </>
  );
};

export default ViewMemberEditTypePage;
