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 { useObjectToEdit } from "../../../../../../zustand/ObjectToEditState";
import { useAddSessionContent } from "../../../../../../api/sessionContent";
import { useTranslation } from "react-i18next";

const ModalForm: React.FC = () => {
  const { isOpen, setIsOpen } = useModalState((state) => state);
  const { mutate, isSuccess, isLoading } = useAddSessionContent();
  const { set_object_to_edit, object_to_edit } = useObjectToEdit();
  useEffect(() => {
    if (isSuccess) {
      setIsOpen("isSuccess");
      set_object_to_edit({});
    }
  }, [setIsOpen, isSuccess, set_object_to_edit]);

  const handleSubmit = (values: any) => {
    const Data_To_Send = { ...values };
    Data_To_Send["date"] = values?.date?.format("YYYY/MM/DD");
    set_object_to_edit(values);
    mutate(Data_To_Send);
  };

  const handleCancel = () => {
    setIsOpen("");
    set_object_to_edit({});
  };
  const [t] = useTranslation();

  return (
    <>
      <Modal
        className="ModalForm"
        centered
        width={"60vw"}
        footer={null}
        open={isOpen === ModalEnum?.HOME_WORK_ADD}
        onCancel={handleCancel}
      >
        <FormikForm
          handleSubmit={handleSubmit}
          initialValues={getInitialValues(object_to_edit)}
          validationSchema={getValidationSchema}
        >
          <header>{t("header.add_session_content")} </header>
          <main className="main_modal w-100">
            <ModelBody />
            <div className="buttons">
              <div onClick={handleCancel}>{t("practical.cancel")} </div>
              <button disabled={isLoading} type="submit">
                {t("practical.add")}
                {isLoading && (
                  <span className="Spinier_Div">
                    <Spin />
                  </span>
                )}
              </button>
            </div>
          </main>
        </FormikForm>
      </Modal>
    </>
  );
};

export default ModalForm;
