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 { useAddCycle } from "../../../../api/cycle";
import { useObjectToEdit } from "../../../../zustand/ObjectToEditState";
import { useTranslation } from "react-i18next";
import { useParams } from "react-router-dom";
import { ParamsEnum } from "../../../../enums/params";

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

  const { branch_id } = useParams<ParamsEnum>();
  const handleSubmit = (values: any) => {
    const dataToSend = {
      ...values,
      starting_date: "",
      ending_date: "",
      branch_id: branch_id,
    };

    if (values?.status === true) {
      dataToSend["status"] = "active";
    }
    if (values?.status === false) {
      dataToSend["status"] = "inActive";
    }
    dataToSend["starting_date"] = values?.starting_date?.format("YYYY-MM-DD");
    dataToSend["ending_date"] = values?.ending_date?.format("YYYY-MM-DD");

    mutate(dataToSend);
  };

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

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

export default ModalForm;
