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

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

  const { mutate, isSuccess, isLoading } = useUpdateLesson();
  const { objectToEdit, setObjectToEdit } = useObjectToEdit();

  const queryClient = useQueryClient();

  // console.log(objectToEdit,"objectToEdit");

  useEffect(() => {
    if (isSuccess) {
      queryClient.invalidateQueries(["unit"]);

      setIsOpen("");
    }
  }, [setIsOpen, isSuccess, queryClient]);

  const handleSubmit = (values: any) => {
    //   console.log(values,"values");
    mutate({
      id: values?.id,
      name: values?.name,
    });
  };

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

  const [t] = useTranslation();
  return (
    <>
      <Modal
        className="ModalForm"
        centered
        width={"40vw"}
        footer={null}
        open={isOpen === ModalEnum?.LESSON_EDIT}
        onCancel={handleCancel}
      >
        <FormikForm
          handleSubmit={handleSubmit}
          initialValues={getInitialValues(objectToEdit)}
          validationSchema={getValidationSchema}
        >
          <header>
            {" "}
            {t("practical.edit")} {t("practical.details")} {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.edit")}

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

export default ModalForm;
