import React, { useEffect } from "react";
import { Divider, Modal, Spin } from "antd";
import { useModalState } from "../../../../zustand/Modal";
import { useObjectToEdit } from "../../../../zustand/ObjectToEditState";
import { useTranslation } from "react-i18next";
import { QueryStatusEnum } from "../../../../enums/QueryStatus";
import SpinContainer from "../../../../Components/Layout/SpinContainer";
import { MdCancel } from "react-icons/md";
import { Form, Formik, useFormikContext } from "formik";

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

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

  const handleCancel = () => {
    setIsOpen("");
    canClearObjectToEdit && setObjectToEdit({});
    formik.resetForm();
  };

  const [t] = useTranslation();
  return (
    <>
      <Modal
        className={"ModalForm " + ModelClassName}
        centered
        width={width}
        footer={null}
        open={isOpen === ModelEnum}
        // onCancel={handleCancel}
      >
        <Formik
          enableReinitialize={true}
          initialValues={getInitialValues}
          validationSchema={getValidationSchema}
          onSubmit={handleSubmit}
          onReset={handleReset}
        >
          {(formik) => {
            useEffect(() => {
              if (isOpen === "" || isOpen === "isSuccess") {
                formik.setErrors({});
                formik.resetForm();
              }
            }, [isOpen]);

            return (
              <Form className="w-100 reseller_modal_form">
                <main className="main_modal">
                  {isLoading ? <SpinContainer /> : children}
                </main>
              </Form>
            );
          }}
        </Formik>
      </Modal>
    </>
  );
};

export default LayoutModel;
