import React, { useEffect, useState } from "react";
import { Input, Modal, Spin } from "antd";
import { useModalState } from "../../../zustand/Modal";
import { ModalEnum } from "../../../enums/Model";
import { useDeleteEduClass, useGetAllEduClass } from "../../../api/eduClass";
import { useNavigate, useParams } from "react-router-dom";
import { useTranslation } from "react-i18next";

const ModalForm: React.FC = () => {
  const { isOpen, setIsOpen } = useModalState((state) => state);
  const [inputValue, setInputValue] = useState("");

  const { mutate, isLoading, isSuccess } = useDeleteEduClass();
  const navigate = useNavigate();

  const { edu_class_id } = useParams();

  const { data: edu_class } = useGetAllEduClass({
    show: edu_class_id,
  });
  const edu_class_name = edu_class?.data?.name || "";
  const course_name = edu_class?.data?.course?.name || "";
  const full_name = " " + course_name + " ( " + edu_class_name + " )";

  useEffect(() => {
    if (isSuccess) {
      navigate(-1);
      setIsOpen("");
      setInputValue("");
    }
  }, [isSuccess, navigate, setIsOpen]);

  const handleSubmit = () => {
    mutate({
      id: Number(edu_class_id),
    });
  };

  const handleCancel = () => {
    setInputValue("");
    setIsOpen("");
  };

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    // Step 2: Handle changes to the input field
    setInputValue(e.target.value);
  };
  const [t] = useTranslation();

  return (
    <>
      <Modal
        className="ModalForm"
        centered
        width={"40vw"}
        footer={null}
        open={isOpen === ModalEnum?.EDUClASS_DELETE}
        onCancel={handleCancel}
      >
        <header>
          {t("practical.delete")} {full_name}{" "}
        </header>
        <main className="main_modal">
          <div className="ValidationField w-100 mb-5">
            <label className="text ">
              {t("practical.to_confirm_deletion_please_re_enter")}{" "}
              {t("input.name")}
            </label>

            <Input
              size="large"
              type="text"
              placeholder={`${t("practical.enter")} ${t("input.name")} `}
              value={inputValue}
              onChange={handleChange}
            />
          </div>

          <div className="buttons">
            <div onClick={handleCancel}>{t("practical.cancel")}</div>
            <button
              className={edu_class_name !== inputValue ? "disabled_button" : ""}
              disabled={edu_class_name !== inputValue || isLoading}
              onClick={handleSubmit}
            >
              {t("practical.delete")}
              {isLoading && (
                <span className="Spinier_Div">
                  <Spin />
                </span>
              )}
            </button>
          </div>
        </main>
      </Modal>
    </>
  );
};

export default ModalForm;
