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 { toast } from "react-toastify";
import dayjs from "dayjs";
import {
  useAddEarlyDeparture,
  useDeleteEarlyDeparture,
  useUpdateEarlyDeparture,
} from "../../../../../../api/earlyDeparture";
import { StudentStatusEnum } from "../../../../../../enums/Items";
import { useQueryClient } from "react-query";
import { useTranslation } from "react-i18next";
import { TERM_OBJECT_KEY } from "../../../../../../config/AppKey";
import { getLocalStorage } from "../../../../../../utils/LocalStorage";

const ModalForm: React.FC = () => {
  const { isOpen, setIsOpen } = useModalState((state) => state);
  const { object_to_edit, param_to_send } = useObjectToEdit((state) => state);

  const {
    mutate: mutate_EarlyDeparture,
    isSuccess: isSuccess_mutate_EarlyDeparture,
    isLoading: isLoading_mutate_EarlyDeparture,
  } = useAddEarlyDeparture();
  const {
    mutate: update_EarlyDeparture,
    isSuccess: isSuccess_update_EarlyDeparture,
    isLoading: isLoading_update_EarlyDeparture,
  } = useUpdateEarlyDeparture();
  const {
    mutate: mutate_presence,
    isSuccess: isSuccess_mutate_presence,
    isLoading: isLoading_mutate_presence,
  } = useDeleteEarlyDeparture();

  const queryClient = useQueryClient();

  console.log(object_to_edit, "object_to_edit");
  let Today = new Date() as any;
  let dateToSend =
    param_to_send?.date === "today"
      ? dayjs(Today).format("YYYY-MM-DD")
      : param_to_send?.date ?? dayjs(Today).format("YYYY-MM-DD");

  const term_id = getLocalStorage(TERM_OBJECT_KEY)?.id;
  const [t] = useTranslation();
  useEffect(() => {
    if (
      isSuccess_mutate_EarlyDeparture ||
      isSuccess_update_EarlyDeparture ||
      isSuccess_mutate_presence
    ) {
      setIsOpen("");
      queryClient.invalidateQueries(["attendence"]);
    }
  }, [
    setIsOpen,
    isSuccess_mutate_EarlyDeparture,
    isSuccess_update_EarlyDeparture,
    isSuccess_mutate_presence,
    queryClient,
  ]);

  const handleSubmit = (values: any) => {
    // console.log(values,"values");
    if (values?.status === StudentStatusEnum?.EARLY_DEPARTURE) {
      if (!values?.departure_time) {
        toast.error(t("validation.duration_is_required"));
        return;
      }

      if (values?.type === "justified") {
        if (!values?.justification) {
          toast.error(t("validation.justification_is_required"));
          return;
        }
      }

      if (object_to_edit?.status === StudentStatusEnum?.EARLY_DEPARTURE) {
        const NewData = {
          id: object_to_edit?.[StudentStatusEnum?.EARLY_DEPARTURE]?.id,
          type: values?.type,
          justification: values?.justification,
          term_id: term_id,
          attachment: values?.attachment,
          departure_time: "",
          date: dateToSend,
        };
        NewData["departure_time"] = values?.departure_time?.format("HH:mm");

        // if (typeof NewData?.attachment === "string") {
        //   delete NewData["attachment"];
        // }

        const formData = new FormData();

        formData.append("id", NewData?.id);
        formData.append("type", NewData?.type);
        formData.append("date", NewData?.date);
        formData.append("justification", NewData?.justification);
        formData.append("term_id", NewData?.term_id as any);
        formData.append("duration", NewData?.departure_time);

        if (typeof NewData?.attachment === "string") {
          delete NewData["attachment"];
        } else if (NewData?.attachment) {
          formData.append("attachment", NewData?.attachment);
        } else {
          formData.append("attachment", "");
        }

        update_EarlyDeparture(formData);
        return;
      }

      // console.log(object_to_edit);

      const NewData = {
        registration_record_id: object_to_edit?.id,
        type: values?.type,
        departure_time: "",
        date: dateToSend,
        justification: values?.justification,
        term_id: term_id,
        attachment: values?.attachment,
      };
      NewData["departure_time"] = values?.departure_time?.format("HH:mm");

      if (typeof NewData?.attachment === "string") {
        delete NewData["attachment"];
      }
      // console.log(NewData);

      mutate_EarlyDeparture(NewData);
    }
    if (values?.status === StudentStatusEnum?.PRESENCE) {
      if (object_to_edit?.status === StudentStatusEnum?.PRESENCE) {
        toast.error(t("validation.pleas_do_any_changes"));
        return;
      }
      mutate_presence({
        id: Number(object_to_edit?.[StudentStatusEnum?.EARLY_DEPARTURE]?.id),
      });
    }
  };

  const handleCancel = () => {
    setIsOpen("");
  };
  // console.log(object_to_edit);

  return (
    <>
      <Modal
        className="ModalForm"
        centered
        width={"60vw"}
        footer={null}
        open={isOpen === ModalEnum?.EARLY_DEPARTURE_EDIT}
        onCancel={handleCancel}
      >
        <FormikForm
          handleSubmit={handleSubmit}
          initialValues={getInitialValues(object_to_edit)}
          validationSchema={getValidationSchema}
        >
          <header>
            {t("practical.edit")} {t("practical.details")} ({" "}
            {object_to_edit?.student?.full_name} ){" "}
          </header>
          <main className="main_modal w-100">
            <ModelBody />
            <div className="buttons">
              <div onClick={handleCancel}>{t("practical.back")}</div>
              <button
                disabled={
                  isLoading_mutate_EarlyDeparture ||
                  isLoading_update_EarlyDeparture ||
                  isLoading_mutate_presence
                }
                type="submit"
              >
                {t("practical.edit")}
                {isLoading_mutate_EarlyDeparture ||
                  isLoading_update_EarlyDeparture ||
                  (isLoading_mutate_presence && (
                    <span className="Spinier_Div">
                      <Spin />
                    </span>
                  ))}
              </button>
            </div>
          </main>
        </FormikForm>
      </Modal>
    </>
  );
};

export default ModalForm;
