import React, { useEffect } from "react";
import { Modal, Spin } from "antd";
import { useModalState } from "../../../zustand/Modal";
import FormikForm from "../../../Layout/Dashboard/FormikFormModel";
import ModelBody from "./Edit";
import { getInitialValues, getValidationSchema } from "./formUtil";
import { ModalEnum } from "../../../enums/Model";
import { useObjectToEdit } from "../../../zustand/ObjectToEditState";
import { useUpdateRole } from "../../../api/role";
import { useTranslation } from "react-i18next";

const ModalForm: React.FC = () => {
  const { isOpen, setIsOpen } = useModalState((state) => state);
  const { object_to_edit, set_object_to_edit } = useObjectToEdit(
    (state) => state,
  );
  const { mutate, isSuccess, isLoading } = useUpdateRole();
  // console.log(object_to_edit,"object_to_edit");
  const handleSubmit = (values: any) => {
    const dataToSend = { ...values };
    if (!values?.abilities) {
      dataToSend["abilities"] = [];
    }
    mutate({
      ...dataToSend,
    });
  };
  const handleCancel = () => {
    setIsOpen("");
    set_object_to_edit({});
  };

  useEffect(() => {
    if (isSuccess) {
      setIsOpen("");
    }
  }, [setIsOpen, isSuccess]);
  const [t] = useTranslation();
  return (
    <Modal
      className="ModalForm"
      centered
      width={"60vw"}
      footer={null}
      open={isOpen === ModalEnum?.ROLE_EDIT}
      onCancel={handleCancel}
    >
      {object_to_edit && (
        <FormikForm
          handleSubmit={handleSubmit}
          initialValues={getInitialValues(object_to_edit)}
          validationSchema={getValidationSchema}
        >
          <header>
            {" "}
            {t("practical.edit")} {t("practical.details")} {t("models.role")}{" "}
          </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.edit")}
                {isLoading && (
                  <span className="Spinier_Div">
                    <Spin />
                  </span>
                )}
              </button>
            </div>
          </main>
        </FormikForm>
      )}
    </Modal>
  );
};

export default ModalForm;
