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 {
  useAddLateArrival,
  useUpdateLateArrival,
} from "../../../../api/lateArrival";
import { StudentStatusEnum } from "../../../../enums/Items";
import { useQueryClient } from "react-query";
import { useAddPresence } from "../../../../api/presence";
import {
  useAddEarlyDeparture,
  useUpdateEarlyDeparture,
} from "../../../../api/earlyDeparture";
import { useParams } from "react-router-dom";
import { useGetStudent } from "../../../../api/student";
import { Student } from "../../../../types/Item";
import { useTranslation } from "react-i18next";
import { getLocalStorage } from "../../../../utils/LocalStorage";
import { TERM_OBJECT_KEY } from "../../../../config/AppKey";

const ModalForm: React.FC = () => {
  const { isOpen, setIsOpen } = useModalState((state) => state);
  const { object_to_edit } = 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 {
    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 queryClient = useQueryClient();

  const term_id = getLocalStorage(TERM_OBJECT_KEY)?.id;

  const { student_id } = useParams();
  const { data: student } = useGetStudent({
    show: student_id,
  });
  const registration_record_id = student?.data?.registration_record_id;
  useEffect(() => {
    if (
      isSuccess_mutate_absence ||
      isSuccess_update_absence ||
      isSuccess_mutate_lateArrival ||
      isSuccess_update_lateArrival ||
      isSuccess_mutate_presence ||
      isSuccess_mutate_EarlyDeparture ||
      isSuccess_update_EarlyDeparture
    ) {
      setIsOpen("");
      queryClient.invalidateQueries(["presence"]);
    }
  }, [
    setIsOpen,
    isSuccess_mutate_absence,
    isSuccess_update_absence,
    isSuccess_mutate_lateArrival,
    isSuccess_update_lateArrival,
    isSuccess_mutate_presence,
    isSuccess_mutate_EarlyDeparture,
    isSuccess_update_EarlyDeparture,
    queryClient,
  ]);

  const [t] = useTranslation();
  const handleSubmit = (values: any) => {
    if (values?.status !== StudentStatusEnum?.PRESENCE) {
      if (values?.type === "justified") {
        if (!values?.justification) {
          toast.error(t("validation.justification_is_required"));
          return;
        }
      }
    }
    if (values?.status === StudentStatusEnum?.ABSENCE) {
      if (object_to_edit?.[StudentStatusEnum?.ABSENCE]?.[0]?.id) {
        const NewData = {
          id: object_to_edit?.[StudentStatusEnum?.ABSENCE]?.[0]?.id,
          type: values?.type,
          date: values?.date,
          justification: values?.justification,
          term_id: term_id,
          attachment: values?.attachment,
        };
        // update_absence(NewData);
        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: registration_record_id,
        type: values?.type,
        date: values?.date,
        justification: values?.justification,
        term_id: term_id,
        attachment: values?.attachment,
      };
      if (typeof NewData?.attachment === "string") {
        delete NewData["attachment"];
      }
      if (!NewData?.attachment) {
        delete NewData["attachment"];
      }
      // NewData["date"] = values?.date?.format("YYYY/MM/DD");

      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 (object_to_edit?.[StudentStatusEnum?.LATE_ARRIVAL]?.[0]?.id) {
        const NewData = {
          id: object_to_edit?.[StudentStatusEnum?.LATE_ARRIVAL]?.[0]?.id,
          type: values?.type,
          justification: values?.justification,
          term_id: term_id,
          attachment: values?.attachment,
          duration: "",
          date: values?.date,
        };
        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: registration_record_id,
        type: values?.type,
        duration: "",
        date: values?.date,
        justification: values?.justification,
        term_id: term_id,
        attachment: values?.attachment,
      };
      NewData["duration"] = values?.duration?.format("HH:mm");
      // NewData["date"] = values?.date?.format("YYYY/MM/DD");

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

      mutate_lateArrival(NewData);
    }
    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?.[StudentStatusEnum?.EARLY_DEPARTURE]?.[0]?.id) {
        const NewData = {
          id: object_to_edit?.[StudentStatusEnum?.EARLY_DEPARTURE]?.[0]?.id,
          type: values?.type,
          justification: values?.justification,
          term_id: term_id,
          attachment: values?.attachment,
          departure_time: "",
          date: values?.date,
        };
        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: registration_record_id,
        type: values?.type,
        departure_time: "",
        date: values?.date,
        justification: values?.justification,
        term_id: term_id,
        attachment: values?.attachment,
      };
      NewData["departure_time"] = values?.departure_time?.format("HH:mm");
      // NewData["date"] = values?.date?.format("YYYY/MM/DD");

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

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

      mutate_EarlyDeparture(NewData);
    }
    if (values?.status === StudentStatusEnum?.PRESENCE) {
      mutate_presence({
        registration_record_id: registration_record_id,
        type: values?.type,
        date: values?.date,
      });
    }
  };

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

  const student_data = student?.data as Student;
  return (
    <>
      <Modal
        className="ModalForm"
        centered
        width={"60vw"}
        footer={null}
        open={isOpen === ModalEnum?.STUDENT_STATUS_EDIT}
        onCancel={handleCancel}
      >
        <FormikForm
          handleSubmit={handleSubmit}
          initialValues={getInitialValues(object_to_edit)}
          validationSchema={getValidationSchema}
        >
          {" "}
          <header>
            {t("practical.edit")} ( {student_data?.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 ||
                  isLoading_mutate_EarlyDeparture ||
                  isLoading_update_EarlyDeparture
                }
                type="submit"
              >
                {t("practical.edit")}

                {isLoading_mutate_absence ||
                  isLoading_update_absence ||
                  isLoading_mutate_lateArrival ||
                  isLoading_update_lateArrival ||
                  isLoading_mutate_presence ||
                  isLoading_update_EarlyDeparture ||
                  (isLoading_mutate_EarlyDeparture && (
                    <span className="Spinier_Div">
                      <Spin />
                    </span>
                  ))}
              </button>
            </div>
          </main>
        </FormikForm>
      </Modal>
    </>
  );
};

export default ModalForm;
