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 ModelForm from "./Model/ModelForm";
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";
import { useGetAllSubject } from "../../api/subject";
import { useGetAllGrade } from "../../api/grade";
import { useGetAllCurriculum } from "../../api/curriculum";

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

  const { setIsOpen } = useModalState((state) => state);

  const [t] = useTranslation();
  const { unit_id, curriculum_id, grade_id, subject_id, lesson_id } =
    useParams<ParamsEnum>();
  const { data: unit } = useGetAllUnit({ show: unit_id });

  const { data: Subject } = useGetAllSubject({
    show: subject_id,
  });
  const { data: grade } = useGetAllGrade({
    show: grade_id,
  });
  const { data: Curriculum } = useGetAllCurriculum({
    show: curriculum_id,
  });
  const { data: Lesson } = useGetAllLesson({
    show: lesson_id,
  });

  const gradeName = grade?.data?.name ?? "";
  const SubjectName = Subject?.data?.name ?? "";
  const CurriculumName = Curriculum?.data?.name ?? "";
  const unitName = unit?.data?.name ?? "";
  const LessonName = Lesson?.data?.name ?? "";

  useSetPageTitle(
    t(`page_header.grade`) +
      "/" +
      gradeName +
      "/" +
      t(`PageTitle.subject`) +
      "/" +
      SubjectName +
      "/" +
      t("PageTitle.curriculum") +
      "/" +
      CurriculumName +
      "/" +
      t("PageTitle.unit") +
      "/" +
      unitName +
      "/" +
      t("PageTitle.lesson") +
      "/" +
      LessonName +
      "/" +
      t("PageTitle.question") +
      "/" +
      t("practical.add"),
  );
  const handleSubmit = (
    values: any,
    { resetForm }: { resetForm: () => void },
  ) => {
    const DataToSend = structuredClone(values);
    console.log(DataToSend);
  
    setTagsSearch(null);
    const canAnswersBeShuffled = DataToSend?.canAnswersBeShuffled ? 1 : 0;
    if (isBseQuestion || DataToSend?.isBase === 1) {
      const newBseQuestion = {
        subject_id: subject_id,
        content: DataToSend?.content,
        image: DataToSend?.image ?? "",
        isBase: 1,
        lessons_ids: [lesson_id],
        canAnswersBeShuffled,
        hint: DataToSend?.hint,
      };

      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);
          const answers = item?.answers?.map((item:any,index:number)=>{
            return {
              order:index,
              ...item
            }
          })
          console.log(answers);

          mutate({    
            ...item,
            parent_id: newBseQuestionId,
            subject_id: subject_id,
            tags,
            lessons_ids: [lesson_id],
            answers
          });
        });
        console.log(newBseQuestionId, "newBseQuestionId");
      });
    } else {
      const tags = processTags(DataToSend);
      console.log(values,"values"); 
      const answers = values?.answers?.map((item:any,index:number)=>{
        return {
          order:index,
          ...item
        }
      })
   
      mutate({
        ...values,
        subject_id: subject_id,
        tags,
        lessons_ids: [lesson_id],
        canAnswersBeShuffled,
        answers
      });
    }
  };

  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 cleanedAnswers = cleanObject(SavedQuestionData);
  let noChange = hasItems(cleanedAnswers);

  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 />
          <ModelForm />

          <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;
