import React, { Suspense, lazy, useEffect } from "react";
import {  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/Form";
import ModelForm from "./Model/ModelForm";
import { toast } from "react-toastify";
const AcceptModal = lazy(() => import("./Model/AcceptModal"));

const AddPage: React.FC = () => {

  const {  mutateAsync } = useAddQuestionAsync();
  const { mutate, isLoading ,isSuccess} = useAddQuestion();
  const {
    isBseQuestion,
    setTagsSearch,
    objectToEdit,
    setSuccess
  } = useObjectToEdit();


  const [t] = useTranslation();
  const {  subject_id, lesson_id } =
    useParams<ParamsEnum>();
  
console.log(objectToEdit,"objectToEdit");

  const handleSubmit = (
    values: any,
    { resetForm }: { resetForm: () => void },
  ) => {

    const DataToSend = structuredClone(values);
    setTagsSearch(null);
    console.log(1);
    
    const canAnswersBeShuffled = DataToSend?.canAnswersBeShuffled ? 1 : 0;

    if (isBseQuestion || DataToSend?.isBase === 1) {
      const newBseQuestion = {
        subject_id: subject_id,
        content: DataToSend?.content,
        content_image: DataToSend?.content_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);
          if(answers?.length > 0){
            const isValidAnswers =  answers?.some((answer:any) => answer?.isCorrect === 1)
            
            if(!isValidAnswers){
              toast.error(t("validation.at_least_one_answer_should_be_correct"));
              return;
            }
            }
          mutate({
            ...item,
            parent_id: newBseQuestionId,
            subject_id: subject_id,
            tags,
            lessons_ids: [lesson_id],
            answers,
          });
        });
        console.log(newBseQuestionId, "newBseQuestionId");
      });
    } else {
      console.log(1);
      
      const tags = processTags(DataToSend);
      const answers = values?.answers?.map((item: any, index: number) => {
        
        return {
          order: index,
          ...item,
        };
      });
      
      if(answers?.length > 0){
        
      const isValidAnswers =  answers?.some((answer:any) => answer?.isCorrect === 1)
        console.log(!isValidAnswers);
        
      if(!isValidAnswers){
        toast.error(t("validation.at_least_one_answer_should_be_correct"));
        return;
      }
      }
   
      const NewQuestion = {
        ...values,
        subject_id: subject_id,
        tags,
        lessons_ids: [lesson_id],
        canAnswersBeShuffled,
        answers,
      };
      console.clear();
      console.log(NewQuestion, "NewQuestion");

      mutate(NewQuestion);
    }
  };

  const navigate = useNavigate();


  const handleCancel = () => {
    navigate(-1);
  };




  
  useEffect(() => {

    
    console.log("all api success");
    if(isSuccess){

      setSuccess(true )
    }
}, [isSuccess])



  if (isBseQuestion) {
    return (
      <div className="exercise_add">
        <FormikForm
          handleSubmit={handleSubmit}
          initialValues={getInitialValuesBase(objectToEdit)}
          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(objectToEdit)}
        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;
