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, getValidationSchemaADD } from "./formUtil";
import { ModalEnum } from "../../../../../../../enums/Model";
import { useObjectToEdit } from "../../../../../../../zustand/ObjectToEditState";
import { useParams } from "react-router-dom";
import { useAddExam } from "../../../../../../../api/exam";
import { useTranslation } from "react-i18next";
import { getLocalStorage } from "../../../../../../../utils/LocalStorage";
import { TERM_OBJECT_KEY } from "../../../../../../../config/AppKey";

const ModalForm: React.FC = () => {
  const { isOpen, setIsOpen } = useModalState((state) => state);
  const { mutate, isSuccess, isLoading } = useAddExam();
  const { set_object_to_edit, object_to_edit } = useObjectToEdit();
  useEffect(() => {
    if (isSuccess) {
      setIsOpen("isSuccess");
      set_object_to_edit({});
    }
  }, [setIsOpen, isSuccess]);
  const term_id = getLocalStorage(TERM_OBJECT_KEY)?.id;
  const { edu_class_id } = useParams();

  const handleSubmit = (values: any) => {
    const dataToSend = {
      ...values,
      date: "",
      duration: "",
      edu_class_id: edu_class_id,
      term_id: term_id,
    };
    dataToSend["date"] = values?.date?.format("YYYY-MM-DD");
    dataToSend["duration"] = values?.duration?.format("HH:mm");
    set_object_to_edit(values);
    console.log(values);

    mutate(dataToSend);
  };

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

  const [t] = useTranslation();
  return (
    <>
      <Modal
        className="ModalForm"
        centered
        width={"60vw"}
        footer={null}
        open={isOpen === ModalEnum?.EXAM_ADD}
        onCancel={handleCancel}
      >
        <FormikForm
          handleSubmit={handleSubmit}
          initialValues={getInitialValues(object_to_edit)}
          validationSchema={getValidationSchemaADD}
        >
          <header>
            {" "}
            {t("practical.add")} {t("models.exam")}{" "}
          </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;
