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 { useAddAbsence, useUpdateAbsence } from "../../../../../../api/absence";
import dayjs from "dayjs";
import {
  useAddLateArrival,
  useUpdateLateArrival,
} from "../../../../../../api/lateArrival";
import { StudentStatusEnum } from "../../../../../../enums/Items";
import { useQueryClient } from "react-query";
import { useAddPresence } from "../../../../../../api/presence";
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, old_object_to_edit, param_to_send } = useObjectToEdit(
    (state) => state,
  );
  const {
    mutate: mutate_absence,
    isSuccess: isSuccess_mutate_absence,
    isLoading: isLoading_mutate_absence,
  } = useAddAbsence();
  const {
    mutate: update_absence,
    isSuccess: isSuccess_update_absence,
    isLoading: isLoading_update_absence,
  } = useUpdateAbsence();

  const {
    mutate: mutate_lateArrival,
    isSuccess: isSuccess_mutate_lateArrival,
    isLoading: isLoading_mutate_lateArrival,
  } = useAddLateArrival();
  const {
    mutate: update_lateArrival,
    isSuccess: isSuccess_update_lateArrival,
    isLoading: isLoading_update_lateArrival,
  } = useUpdateLateArrival();

  const {
    mutate: mutate_presence,
    isSuccess: isSuccess_mutate_presence,
    isLoading: isLoading_mutate_presence,
  } = useAddPresence();

  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;

  useEffect(() => {
    if (
      isSuccess_mutate_absence ||
      isSuccess_update_absence ||
      isSuccess_mutate_lateArrival ||
      isSuccess_update_lateArrival ||
      isSuccess_mutate_presence
    ) {
      setIsOpen("");
      queryClient.invalidateQueries(["attendence"]);
    }
  }, [
    setIsOpen,
    isSuccess_mutate_absence,
    isSuccess_update_absence,
    isSuccess_mutate_lateArrival,
    isSuccess_update_lateArrival,
    isSuccess_mutate_presence,
    queryClient,
  ]);

  const [t] = useTranslation();
  const handleSubmit = (values: any) => {
    console.log(values?.status, "values");
    console.log(old_object_to_edit?.status, "object_to_edit");

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

      if (old_object_to_edit?.status === StudentStatusEnum?.ABSENCE) {
        const NewData = {
          id: object_to_edit?.[StudentStatusEnum?.ABSENCE]?.id,
          type: values?.type,
          date: dateToSend,
          justification: values?.justification,
          term_id: term_id,
          attachment: values?.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);

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

        update_absence(formData);
        return;
      }
      const NewData = {
        registration_record_id: object_to_edit?.id,
        type: values?.type,
        date: dateToSend,
        justification: values?.justification,
        term_id: term_id,
        attachment: values?.attachment,
      };
      if (typeof NewData?.attachment === "string") {
        delete NewData["attachment"];
      }

      mutate_absence(NewData);
    }
    if (values?.status === StudentStatusEnum?.LATE_ARRIVAL) {
      if (values?.type === "justified") {
        if (!values?.justification) {
          toast.error(t("validation.justification_is_required"));
          return;
        }
      }
      if (!values?.duration) {
        toast.error(t("validation.duration_is_required"));
        return;
      }

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

        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?.duration);

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

        update_lateArrival(formData);
        return;
      }

      // console.log(object_to_edit);

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

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

      mutate_lateArrival(NewData);
    }
    if (values?.status === StudentStatusEnum?.PRESENCE) {
      if (old_object_to_edit?.status === StudentStatusEnum?.PRESENCE) {
        toast.error(t("validation.pleas_do_any_changes"));
        return;
      }
      mutate_presence({
        registration_record_id: object_to_edit?.id,
        type: values?.type,
        date: dateToSend,
      });
    }
  };

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

  return (
    <>
      <Modal
        className="ModalForm"
        centered
        width={"60vw"}
        footer={null}
        open={isOpen === ModalEnum?.ABSENCE_EDIT}
        onCancel={handleCancel}
      >
        <FormikForm
          handleSubmit={handleSubmit}
          initialValues={getInitialValues(object_to_edit)}
          validationSchema={getValidationSchema}
        >
          <header>
            {t("practical.edit")} ( {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_absence ||
                  isLoading_update_absence ||
                  isLoading_mutate_lateArrival ||
                  isLoading_update_lateArrival ||
                  isLoading_mutate_presence
                }
                type="submit"
              >
                {t("practical.edit")}
                {isLoading_mutate_absence ||
                  isLoading_update_absence ||
                  isLoading_mutate_lateArrival ||
                  isLoading_update_lateArrival ||
                  isLoading_mutate_presence ||
                  (isLoading_mutate_presence && (
                    <span className="Spinier_Div">
                      <Spin />
                    </span>
                  ))}
              </button>
            </div>
          </main>
        </FormikForm>
      </Modal>
    </>
  );
};

export default ModalForm;
