import React, { useEffect } from "react";
import { Modal, Spin } from "antd";
import { useModalState } from "../../../zustand/Modal";
import ModelBody from "./Edit";
import { getInitialValues, getValidationSchema } from "./formUtil";
import { ModalEnum } from "../../../enums/Model";
import { useUpdateSubject } from "../../../api/subject";
import { useObjectToEdit } from "../../../zustand/ObjectToEditState";
import { Form, Formik } from "formik";
import { handelImageState } from "../../../utils/DataToSendImageState";
import { useTranslation } from "react-i18next";

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

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

  useEffect(() => {
    if (isSuccess) {
      setIsOpen("");
      setObjectToEdit({});
    }
  }, [isSuccess]);

  const handleSubmit = (values: any) => {
    const Data_to_send = { ...values };
    const handelImage = handelImageState(Data_to_send, "image");
    mutate(handelImage);
  };

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

  return (
    <>
      <Modal
        className="ModalForm"
        centered
        width={"60vw"}
        footer={null}
        open={isOpen === ModalEnum?.SUBJECT_EDIT}
        onCancel={handleCancel}
      >
        <Formik
          enableReinitialize
          initialValues={getInitialValues(objectToEdit)}
          validationSchema={getValidationSchema}
          onSubmit={handleSubmit}
        >
          {({ values }) => (
            <Form className="w-100">
              <header>
                {t("practical.edit")} {t("models.subject")}{" "}
              </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.edit")}

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

export default ModalForm;
