import React, { useEffect } from "react";
import { Modal, Spin } from "antd";
import { useModalState } from "../../../zustand/Modal";
import FormikForm from "../../../Layout/Dashboard/FormikFormModel";
import ModelBody from "./Add";
import { getInitialValues, getValidationSchema } from "./formUtil";
import { ModalEnum } from "../../../enums/Model";
import { useAddLesson } from "../../../api/lesson";
import { useObjectToEdit } from "../../../zustand/ObjectToEditState";
import { useQueryClient } from "react-query";
import { useTranslation } from "react-i18next";
import { useParams } from "react-router-dom";
import { ParamsEnum } from "../../../enums/params";

const ModalForm: React.FC = () => {
  const { isOpen, setIsOpen } = useModalState((state) => state);
  const { objectToEdit, setObjectToEdit } = useObjectToEdit();

  const queryClient = useQueryClient();

  const { mutate, isSuccess, isLoading } = useAddLesson();

  const {unit_id} = useParams<ParamsEnum>()
  useEffect(() => {
    if (isSuccess) {
      setIsOpen("");
      queryClient.invalidateQueries(["Lesson"]);
    }
  }, [setIsOpen, isSuccess, queryClient]);

  const handleSubmit = (values: any) => {
    mutate({ ...values, unit_id: unit_id });
  };

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

  const [t] = useTranslation();
  return (
    <>
      <Modal
        className="ModalForm"
        centered
        width={"40vw"}
        footer={null}
        open={isOpen === ModalEnum?.LESSON_ADD}
        onCancel={handleCancel}
      >
        <FormikForm
          handleSubmit={handleSubmit}
          initialValues={getInitialValues([])}
          validationSchema={getValidationSchema}
        >
          <header>
            {" "}
            {t("practical.add")} {t("models.lesson")}{" "}
          </header>
          <main className="main_modal w-100">
            <ModelBody />
            <div className="buttons">
              <div onClick={handleCancel}>{t("practical.back")}</div>
              <button disabled={isLoading} type="submit">
                {t("practical.add")}

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

export default ModalForm;
