import React, { 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,
  useDeleteQuestion,
  useGetAllQuestion,
  useUpdateQuestion,
} 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 { removeStringKeys } from "../../../utils/removeStringKeys";
import SpinContainer from "../../../Components/Layout/SpinContainer";
import ModelForm from "./Model/ModelForm";
import BaseForm from "./Model/Malty/Form";
import { Question } from "../../../types/Item";
import { toast } from "react-toastify";


const EditPage: React.FC = () => {
  const {
    subject_id,
    lesson_id,
    question_id,
  } = useParams<ParamsEnum>();
  const { isBseQuestion, setIsBseQuestion, setTagsSearch, DeletedQuestions } =
    useObjectToEdit();

  const { mutate, isSuccess, isLoading } = useUpdateQuestion();
  const { mutate: DeleteQuestion } = useDeleteQuestion();
  const { mutate: mutateAdd } = useAddQuestion();

  const { data, isLoading: dataLoading } = useGetAllQuestion({
    show: question_id,
  });

  const { data: Questions, isLoading: QuestionsDataLoading } =
    useGetAllQuestion({
      parent_id: question_id,
    });

  const objectToEdit = { ...data?.data, Questions: Questions?.data };

  useEffect(() => {
    if (objectToEdit?.isBase && isBseQuestion !== true) {
      setIsBseQuestion(true);
    }
  }, [objectToEdit?.isBase]);

  const [t] = useTranslation();



  const handleSubmit = (values: any) => {
    const DataToSend = structuredClone(values);
    setTagsSearch(null);
    console.log(DataToSend);

    if (isBseQuestion) {
      const UpdateBseQuestion = {
        id: DataToSend?.id,
        content: DataToSend?.content,
        content_image: DataToSend?.content_image ?? "",
      };
      if (
        typeof UpdateBseQuestion?.content_image === "string" &&
        UpdateBseQuestion?.content_image !== ""
      ) {
        delete UpdateBseQuestion["content_image"];
      }
      console.log(DeletedQuestions, "DeletedQuestions");
      console.log(UpdateBseQuestion);

      mutate(UpdateBseQuestion);

      DeletedQuestions?.map((item: any) => {
        DeleteQuestion({ id: item?.id });
      });

      const Questions = DataToSend?.Questions;
      console.log(Questions, "Questions");

      Questions?.map((item: Question) => {
        console.log(item);
        if (item?.id) {
          const itemToSend = structuredClone(item);
          const keysToRemove = ["content_image"];
          const updatedObject = removeStringKeys(itemToSend, keysToRemove);
          console.log(updatedObject, "updatedObject");

          const tags = processTags(updatedObject);
          const oldAnswers = [] as any;
          const newAnswers = [] as any;

          updatedObject?.answers?.forEach((item: any) => {
            if (item?.id) {
              oldAnswers.push({...item,isCorrect:item?.isCorrect ? 1 : 0});
            } else {
              newAnswers.push({...item,isCorrect:item?.isCorrect ? 1 : 0});
            }
          });
          const answers = {
            old: oldAnswers,
            new: newAnswers,
          };
          console.log(answers);

          mutate({
            ...updatedObject,
            answers,
            tags,
          });
        } else {
          console.log(values?.id);

          const tags = processTags(DataToSend);
          mutateAdd({
            ...item,
            subject_id: subject_id,
            tags,
            lessons_ids: [lesson_id],
            parent_id: values?.id,
          });
        }
      });
    } else {
      
      const keysToRemove = ["content_image"];
      console.log(DataToSend);
      const updatedObject = removeStringKeys(DataToSend, keysToRemove);
      delete updatedObject["parent_id"];
      const tags = processTags(updatedObject);
      if (!updatedObject?.content_image) {
        updatedObject["content_image"] = "";
      }

      const oldAnswers = [] as any;
      const newAnswers = [] as any;

      updatedObject?.answers?.forEach((item: any) => {
        if (item?.id) {
          oldAnswers.push({...item,isCorrect:item?.isCorrect ? 1 : 0});
        } else {
          newAnswers.push({...item,isCorrect:item?.isCorrect ? 1 : 0});
        }
      });

      const answers = {
        old: oldAnswers,
        new: newAnswers,
      };

      mutate({ ...updatedObject, answers, tags });
    }
  };

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

  useEffect(() => {
    if (isSuccess) {
      toast.success(t("validation.the_possess_done_successful"));
      navigate(-1);
    }
  }, [isSuccess]);

  if (dataLoading || QuestionsDataLoading) {
    return <SpinContainer />;
  }
  if (objectToEdit?.isBase) {
    return (
      <div className="exercise_add">
        <FormikForm
          handleSubmit={handleSubmit}
          initialValues={getInitialValuesBase(objectToEdit)}
          validationSchema={getValidationSchemaBase}
        >
          <main className="w-100 exercise_add_main">
            {/* <Header/> */}
            <header className="exercise_add_header mb-4">
              <div>
                {t("practical.edit")} {t("models.exercise")}{" "}
              </div>
              <div>{t("header.exercise")}</div>
            </header>
            <BaseForm />
            <div className="exercise_add_buttons">
              <div onClick={handleCancel}>{t("practical.back")}</div>
              <button disabled={isLoading} className="relative" type="submit">
                {t("practical.edit")}

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

  return (
    <div className="exercise_add">
      <FormikForm
        handleSubmit={handleSubmit}
        initialValues={getInitialValues(objectToEdit)}
        validationSchema={getValidationSchema}
      >
        <main className="w-100 exercise_add_main">
          {/* <Header/> */}
          <header className="exercise_add_header mb-4">
            <div>
              {t("practical.edit")} {t("models.exercise")}{" "}
            </div>
            <div>{t("header.exercise")}</div>
          </header>
          <ModelForm />
          <div className="exercise_add_buttons">
            <div onClick={handleCancel}>{t("practical.back")}</div>
            <button disabled={isLoading} className="relative" type="submit">
              {t("practical.edit")}

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

export default EditPage;
