import React, { useEffect } from "react";
import { Modal } from "antd";
import { useModalState } from "../../../../../zustand/Modal";
import FormikForm from "../../../../../Layout/Dashboard/FormikForm";
import ModelBody from "./ModelBody";
import TabsSubmite from "./TabsSubmite";
import { getInitialValues, getValidationSchema } from "./formUtil";
import { ModalEnum } from "../../../../../enums/Model";
import { useAddStudent } from "../../../../../api/student";
import { useParams } from "react-router-dom";
import { useModalTabsState } from "../../../../../zustand/ModalTabsState";

const ModalForm: React.FC = () => {
  const { isOpen, setIsOpen } = useModalState((state) => state);
  const { mutate, isSuccess, isLoading } = useAddStudent();
  const { edu_class_id } = useParams();
  const handleSubmit = (values: any) => {
    const Data_To_Send = { ...values };
    delete Data_To_Send["id"];

    Data_To_Send.attachments = [];
    if (Data_To_Send.attachment1 !== null) {
      Data_To_Send.attachments.push({
        name: "attachment1",
        file: Data_To_Send.attachment1,
      });
    }

    if (Data_To_Send.attachment2 !== null) {
      Data_To_Send.attachments.push({
        name: "attachment2",
        file: Data_To_Send.attachment2,
      });
    }

    Data_To_Send["edu_class_id"] = edu_class_id;
    Data_To_Send["birthday"] = values.birthday?.format(
      "YYYY-MM-DD HH:mm:ss.SSS",
    );

    if (!values?.attachment1) {
      delete Data_To_Send["attachments"];
    }
    // console.log(Data_To_Send);
    mutate(Data_To_Send);
  };
  const { setActiveTab } = useModalTabsState((state) => state);

  useEffect(() => {
    if (isSuccess) {
      setActiveTab(4);
      getInitialValues([]);
    }
  }, [isSuccess, setActiveTab]);

  return (
    <>
      <Modal
        className="AddModalForm"
        centered
        width={"80vw"}
        footer={null}
        open={isOpen === ModalEnum.STUDENT_ADD}
        onOk={() => setIsOpen("")}
        onCancel={() => setIsOpen("")}
      >
        <FormikForm
          handleSubmit={handleSubmit}
          initialValues={getInitialValues([])}
          validationSchema={getValidationSchema}
        >
          <ModelBody />
          <TabsSubmite isLoading={isLoading} steps={4} />
        </FormikForm>
      </Modal>
    </>
  );
};

export default ModalForm;
