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 { useObjectToEdit } from "../../../../../../zustand/ObjectToEditState";
import { useMoveStudent } from "../../../../../../api/student";
import { useQueryClient } from "react-query";
import { useTranslation } from "react-i18next";

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

  const { mutate, isSuccess, isLoading } = useMoveStudent();
  const { object_ids } = useObjectToEdit((state) => state);

  const { edu_class_id } = useParams();
  const { data } = useGetAllEduClass(
    {
      all: "all",
    },
    { enabled: isOpen === ModalEnum?.STUDENT_MOVE },
  );

  const eduClassData: any[] = data?.data || [];

  const filteredEduClasses: any[] =
    eduClassData?.length > 0
      ? eduClassData?.filter(
          (eduClass: any) => eduClass?.id !== Number(edu_class_id),
        )
      : [];

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

  useEffect(() => {
    if (isSuccess) {
      setIsOpen("");
      queryClient.invalidateQueries(["student"]);
    }
  }, [isSuccess, setIsOpen]);
  const registraion_records = object_ids?.map((item: any) => {
    return item?.registration_record_id;
  });

  const handleSubmit = () => {
    if (object_ids?.length === 0) {
      toast.error(t("validation.please_select_students"));
      return;
    }
    if (selectValue === null) {
      toast.error(t("validation.please_fill_in_all_the_fields"));

      return;
    } else {
      mutate({
        edu_class_id: selectValue,
        registraion_records: registraion_records,
      });
    }
  };

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

  const handleChangeSelect = (value: any | null) => {
    setSelectValue(value);
  };
  const [t] = useTranslation();
  return (
    <>
      <Modal
        className="ModalForm"
        centered
        width={"40vw"}
        footer={null}
        open={isOpen === ModalEnum?.STUDENT_MOVE}
        onCancel={handleCancel}
      >
        <header>
          {t("practical.move")} {t("models.students")}{" "}
        </header>
        <main className="main_modal">
          <div className="ValidationField w-100 mb-5">
            <label>
              {t("input.name")} {t("models.education_class")}{" "}
            </label>
            <Select
              size="large"
              placeholder={`${t("input.name")}  ${t("models.education_class")}`}
              value={selectValue}
              options={formattedEduClasses}
              onChange={handleChangeSelect}
            />
          </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;
