import React, { useEffect, useState } from "react";
import { Modal, Select, Spin } from "antd";
import { useModalState } from "../../../../../../zustand/Modal";
import { ModalEnum } from "../../../../../../enums/Model";
import { useGetAllEduClass } from "../../../../../../api/eduClass";
import { useParams } from "react-router-dom";
import { toast } from "react-toastify";
import useFormatDataToSelect from "../../../../../../utils/useFormatDataToSelect";
import { useImportStudent } from "../../../../../../api/student";
import useFormatAuthDataToSelect from "../../../../../../utils/useFormatAuthDataToSelect";
import { useGetAllCycle } from "../../../../../../api/cycle";
import { useQueryClient } from "react-query";
import { useTranslation } from "react-i18next";
import { getLocalStorage } from "../../../../../../utils/LocalStorage";
import { CYCLE_OBJECT_KEY } from "../../../../../../config/AppKey";

const ModalForm: React.FC = () => {
  const { isOpen, setIsOpen } = useModalState((state) => state);
  const [selectValue, setSelectValue] = useState<any | null>(null);
  const [SelectCycleValue, setSelectCycleValue] = useState<any | null>(null);

  const { mutate, isSuccess, isLoading } = useImportStudent();
  const cycle_id = getLocalStorage(CYCLE_OBJECT_KEY)?.id;

  const { edu_class_id } = useParams();

  const { data } = useGetAllEduClass(
    {
      cycle_id: SelectCycleValue,
    },
    { enabled: !!SelectCycleValue },
  );
  const eduClassData: any[] = data?.data || [];

  const formattedEduClasses: any = useFormatDataToSelect(eduClassData);
  const queryClient = useQueryClient();

  useEffect(() => {
    if (isSuccess) {
      setIsOpen("");
      queryClient.invalidateQueries(["student"]);
    }
  }, [isSuccess, setIsOpen]);

  const { data: CycleData } = useGetAllCycle(
    {},
    {
      enabled: isOpen === ModalEnum?.STUDENT_TRANSFORM,
    },
  );

  const filteredCycle: any[] =
    CycleData?.data?.length > 0
      ? CycleData?.data?.filter((cycle: any) => cycle?.id !== Number(cycle_id))
      : [];

  const BranchCycleData = useFormatAuthDataToSelect(filteredCycle);

  const [t] = useTranslation();
  const handleSubmit = () => {
    if (selectValue === null) {
      toast.error(t("validation.please_fill_in_all_the_fields"));
      return;
    } else {
      mutate({
        // edu_class_id:edu_class_id,
        // registraion_records:registraion_records
        cycle_id: SelectCycleValue,
        new_edu_class_id: selectValue,
        old_edu_class_id: edu_class_id,
      });
    }
  };

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

  const handleChangeSelect = (value: any | null) => {
    setSelectValue(value);
  };

  const handleChangeCycleSelect = (value: any | null) => {
    setSelectCycleValue(value);
  };
  return (
    <>
      <Modal
        className="ModalForm "
        centered
        width={"40vw"}
        footer={null}
        open={isOpen === ModalEnum?.STUDENT_TRANSFORM}
        onCancel={handleCancel}
      >
        <header>{t("practical.export_students")} </header>
        <main className="main_modal">
          <div className="ValidationField w-100 mb-5">
            <label className="text ">{t("input.academic_year")} </label>
            <Select
              size="large"
              placeholder={`${t("input.academic_year")}`}
              value={SelectCycleValue}
              options={BranchCycleData} // Ensure options are correctly formatted
              onChange={handleChangeCycleSelect}
              className="mb-4"
            />
            <label className="text ">
              {t("input.name")} {t("models.education_class")}
            </label>
            <Select
              size="large"
              placeholder={`${t("input.name")}  ${t("models.education_class")}`}
              value={selectValue}
              options={formattedEduClasses} // Ensure options are correctly formatted
              onChange={handleChangeSelect}
              disabled={!SelectCycleValue}
            />
          </div>

          <div className="buttons">
            <div onClick={handleCancel}>{t("practical.back")}</div>
            <button
              disabled={selectValue === null || isLoading}
              onClick={handleSubmit}
            >
              {t("practical.move")}
              {isLoading && (
                <span className="Spinier_Div">
                  <Spin />
                </span>
              )}
            </button>
          </div>
        </main>
      </Modal>
    </>
  );
};

export default ModalForm;
