import React, { Suspense, lazy, useEffect } from "react";
import { Modal, Spin } from "antd";
import FormikForm from "../../Layout/Dashboard/FormikFormModel";
import {
  getInitialValues,
  getValidationSchema,
  getInitialValuesBase,
  getValidationSchemaBase,
  processTags,
} from "./Model/formUtil";
import { useAddQuestion, useAddQuestionAsync } from "../../api/Question";
import { useTranslation } from "react-i18next";
import { useNavigate, useParams } from "react-router-dom";
import { ParamsEnum } from "../../enums/params";
import { useObjectToEdit } from "../../zustand/ObjectToEditState";

import Header from "../../Components/exercise/Header";
import { Question } from "../../types/Item";
import BaseForm from "./Model/Malty/Add";
import Form from "./Model/Add";
const AcceptModal = lazy(() => import("./Model/AcceptModal"));

import { useModalState } from "../../zustand/Modal";
import { ModalEnum } from "../../enums/Model";
import { cleanObject } from "../../utils/cleanObject";
import { hasItems } from "../../utils/hasItems";
import { QUESTION_OBJECT_KEY } from "../../config/AppKey";
import useSaveOnDisconnect from "../../Hooks/useSaveOnDisconnect";
import { getLocalStorageQuestions } from "../../utils/setLocalStorageQuestions";
import { toast } from "react-toastify";
import useSetPageTitle from "../../Hooks/useSetPageTitle";
import { useGetAllUnit } from "../../api/unit";
import { useGetAllLesson } from "../../api/lesson";

const AddPage: React.FC = () => {
  const { isSuccess: isSuccessAsync, mutateAsync } = useAddQuestionAsync();
  const { mutate, isSuccess, isLoading } = useAddQuestion();
  const {
    isBseQuestion,
    setTagsSearch,
    setObjectToEdit,
    setSuccess,
    SavedQuestionData,
  } = useObjectToEdit();

  const { subject_id, lesson_id, unit_id } = useParams<ParamsEnum>();
  const { setIsOpen } = useModalState((state) => state);

  const { data: unit } = useGetAllUnit({ show: unit_id });
  const { data: lesson } = useGetAllLesson({ show: lesson_id });

  const [t] = useTranslation();
  const unitName = unit?.data?.name ?? "";
  const SubjectName = unit?.data?.subject?.name ?? "";
  const lessonName = lesson?.data?.name ?? "";

  useSetPageTitle(
    t(`page_header.subject`) +
      "/" +
      `${SubjectName}` +
      "/" +
      t(`page_title.unit`) +
      "/" +
      `${unitName}` +
      "/" +
      t(`page_title.lesson`) +
      "/" +
      `${lessonName}` +
      "/" +
      t(`page_title.questions`),
  );

  const handleSubmit = (
    values: any,
    { resetForm }: { resetForm: () => void },
  ) => {
    const DataToSend = structuredClone(values);
    setTagsSearch(null);
    console.log(isBseQuestion);

    if (isBseQuestion || DataToSend?.isBase === 1) {
      const newBseQuestion = {
        subject_id: subject_id,
        content: DataToSend?.content,
        image: DataToSend?.image ?? "",
        isBase: 1,
        lessons_ids: [lesson_id],
      };

      mutateAsync(newBseQuestion).then((data: any) => {
        const newBseQuestionId = (data as any)?.data?.id;
        const Questions = DataToSend?.Questions;
        console.log(1);

        Questions?.map((item: Question) => {
          const tags = processTags(item);
          console.log(item);

          mutate({
            ...item,
            parent_id: newBseQuestionId,
            subject_id: subject_id,
            tags,
            lessons_ids: [lesson_id],
          });
        });
        console.log(newBseQuestionId, "newBseQuestionId");
      });
    } else {
      const tags = processTags(DataToSend);
      mutate({
        ...values,
        subject_id: subject_id,
        tags,
        lessons_ids: [lesson_id],
      });
    }
  };

  const navigate = useNavigate();

  useEffect(() => {
    if (
      isSuccessAsync &&
      (SavedQuestionData?.Questions?.length > 0 ? isSuccess : true)
    ) {
      setObjectToEdit(null);
      setSuccess(true);
      localStorage.removeItem(QUESTION_OBJECT_KEY);
    }
    if (isSuccess && !SavedQuestionData?.Questions?.length) {
      toast.success(t("validation.the_possess_done_successful"));
      setObjectToEdit(null);
      setSuccess(true);
      localStorage.removeItem(QUESTION_OBJECT_KEY);
    }
  }, [isSuccess, isSuccessAsync]);

  let cleanedQuestionOptions = cleanObject(SavedQuestionData);
  let noChange = hasItems(cleanedQuestionOptions);

  useSaveOnDisconnect(noChange, QUESTION_OBJECT_KEY, SavedQuestionData);

  const SavedData = getLocalStorageQuestions(QUESTION_OBJECT_KEY);

  const handleCancel = () => {
    if (!noChange) {
      navigate(-1);
      localStorage.removeItem(QUESTION_OBJECT_KEY);
    } else {
      setIsOpen(ModalEnum?.QUESTION_ACCEPT);
    }
  };

  if (isBseQuestion || SavedData?.isBase === 1) {
    return (
      <div className="exercise_add">
        <FormikForm
          handleSubmit={handleSubmit}
          initialValues={getInitialValuesBase(SavedData)}
          validationSchema={getValidationSchemaBase}
        >
          <main className="w-100 exercise_add_main">
            <Header />
            <BaseForm />
            <div className="exercise_add_buttons">
              <div onClick={handleCancel}>{t("practical.back")}</div>
              <button disabled={isLoading} className="relative" type="submit">
                {t("practical.add")}

                {isLoading && (
                  <span className="Spinier_Div">
                    <Spin />
                  </span>
                )}
              </button>
            </div>
          </main>
        </FormikForm>
        <Suspense fallback={<Spin />}>
          <AcceptModal />
        </Suspense>
      </div>
    );
  }
  return (
    <div className="exercise_add">
      <FormikForm
        handleSubmit={handleSubmit}
        initialValues={getInitialValues(SavedData)}
        validationSchema={getValidationSchema}
      >
        <main className="w-100 exercise_add_main">
          <Header />
          <Form />

          <div className="exercise_add_buttons">
            <div onClick={handleCancel}>{t("practical.back")}</div>
            <button disabled={isLoading} className="relative" type="submit">
              {t("practical.add")}

              {isLoading && (
                <span className="Spinier_Div">
                  <Spin />
                </span>
              )}
            </button>
          </div>
        </main>
      </FormikForm>
      <Suspense fallback={<Spin />}>
        <AcceptModal />
      </Suspense>
    </div>
  );
};

export default AddPage;
