import React, { useEffect, useState } from "react";
import { Input, Modal, Spin } from "antd";
import { useModalState } from "../../../../../../../zustand/Modal";
import { ModalEnum } from "../../../../../../../enums/Model";
import { useDeleteLesson } from "../../../../../../../api/lesson";
import { useObjectToEdit } from "../../../../../../../zustand/ObjectToEditState";
import { useQueryClient } from "react-query";
import { useTranslation } from "react-i18next";

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

  const { mutate, isSuccess, isLoading } = useDeleteLesson();
  const { objectToEdit } = useObjectToEdit((state) => state);
  const queryClient = useQueryClient();
  const [t] = useTranslation();
  const handleSubmit = () => {
    mutate({
      id: Number(objectToEdit?.id),
    });
  };
  useEffect(() => {
    if (isSuccess) {
      setIsOpen("");
      setInputValue("");

      queryClient.invalidateQueries(["unit"]);
    }
  }, [setIsOpen, isSuccess, queryClient]);

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

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setInputValue(e.target.value);
  };

  return (
    <>
      <Modal
        className="ModalForm"
        centered
        width={"40vw"}
        footer={null}
        open={isOpen === ModalEnum?.LESSON_DELETE}
        onCancel={handleCancel}
      >
        <header>
          {" "}
          {t("practical.delete")} {objectToEdit?.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("models.lesson")} {t("input.name")}
            </label>

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

          <div className="buttons">
            <div onClick={handleCancel}>{t("practical.cancel")}</div>
            <button
              className={
                objectToEdit?.name !== inputValue ? "disabled_button" : ""
              }
              disabled={objectToEdit?.name !== inputValue || isLoading}
              onClick={handleSubmit}
            >
              {t("practical.delete")}

              {isLoading && (
                <span className="Spinier_Div">
                  <Spin />
                </span>
              )}
            </button>
          </div>
        </main>
      </Modal>
    </>
  );
};

export default ModalForm;
