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 { useUpdateNote } from "../../../../../../api/note";
import { areArraysEqual } from "../../../../../../utils/areArraysEqual";
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 } = useUpdateNote();
  // console.log(object_to_edit, "object_to_edit");

  const handleSubmit = (values: any) => {
    const data_to_send = { ...values };

    const formData = new FormData();

    formData.append("id", data_to_send?.id);
    formData.append(
      "registration_record_id",
      data_to_send?.registration_record_id,
    );
    formData.append("type", data_to_send?.type);
    formData.append("content", data_to_send?.content);

    if (values?.date) {
      formData.append("date", data_to_send?.date?.format("YYYY/MM/DD"));
    }
    const isEqual = areArraysEqual(
      values?.attachments,
      object_to_edit?.attachments,
    );

    if (areArraysEqual(values?.attachments, object_to_edit?.attachments)) {
      mutate(formData);
      return;
    }
    if (values?.attachments && Array.isArray(values?.attachments)) {
      values.attachments.forEach((attachment: any, index: number) => {
        if (typeof attachment === "object" && attachment?.id) {
          formData.append(`attachments[${index}]`, attachment.id);
        } else {
          formData.append(`attachments[${index}]`, attachment);
        }
      });
    }
    if (values?.attachments === null) {
      formData.append("attachments", [] as any);
    }

    mutate(formData);
  };
  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?.NOTES_EDIT}
      onCancel={handleCancel}
    >
      {object_to_edit && (
        <FormikForm
          handleSubmit={handleSubmit}
          initialValues={getInitialValues(object_to_edit)}
          validationSchema={getValidationSchema}
        >
          <header>
            {" "}
            {t("practical.edit")} {t("models.note")}{" "}
          </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;
