import React, { useEffect } from "react";
import { Modal, Spin } from "antd";
import { useModalState } from "../../zustand/Modal";
import FormikForm from "./FormikFormModel";
import { useObjectToEdit } from "../../zustand/ObjectToEditState";
import { useTranslation } from "react-i18next";
import { QueryStatusEnum } from "../../enums/QueryStatus";
import SpinContainer from "../../Components/Layout/SpinContainer";

interface LayoutModalProps {
  isAddModal?: boolean;
  modelTitle: string;
  handleSubmit: (values: any) => void;
  getInitialValues: any;
  getValidationSchema: any;
  children: React.ReactNode;
  status: QueryStatusEnum;
  ModelEnum: any;
  ModelClassName?: string;
  width?: string;
  isLoading?: boolean;
}

const LayoutModel = ({
  isAddModal = true,
  children,
  handleSubmit = () => {},
  getInitialValues,
  getValidationSchema,
  status,
  modelTitle,
  ModelEnum,
  ModelClassName,
  width = "60vw",
  isLoading = false,
}: LayoutModalProps) => {
  const { isOpen, setIsOpen } = useModalState((state) => state);
  const { setObjectToEdit } = useObjectToEdit();
  useEffect(() => {
    if (isAddModal && status === QueryStatusEnum.SUCCESS) {
      setIsOpen("isSuccess");
      setObjectToEdit({});
      return;
    }
    if (status === QueryStatusEnum.SUCCESS) {
      setIsOpen("");
      setObjectToEdit({});
    }
  }, [setIsOpen, status]);

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

  const [t] = useTranslation();
  return (
    <>
      <Modal
        className={"ModalForm " + ModelClassName}
        centered
        width={width}
        footer={null}
        open={isOpen === ModelEnum}
        onCancel={handleCancel}
      >
        <FormikForm
          handleSubmit={handleSubmit}
          initialValues={getInitialValues}
          validationSchema={getValidationSchema}
        >
          <header>
            {t(`practical.${isAddModal ? "add" : "edit"}`)}{" "}
            {t(`models.${modelTitle}`)}{" "}
          </header>
          <main className="main_modal w-100">
            {isLoading ? <SpinContainer /> : children}
            <div className="buttons">
              <div className="back_button" onClick={handleCancel}>
                {t("practical.back")}
              </div>
              <button
                className="add_button"
                disabled={status === QueryStatusEnum.LOADING}
                type="submit"
              >
                {t(`practical.${isAddModal ? "add" : "edit"}`)}
                {status === QueryStatusEnum.LOADING && (
                  <span className="Spinier_Div">
                    <Spin />
                  </span>
                )}
              </button>
            </div>
          </main>
        </FormikForm>
      </Modal>
    </>
  );
};

export default LayoutModel;
