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 { useQueryClient } from "react-query";
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 Form from "./Model/Edit";
import BaseForm from "./Model/Malty/Edit";
import { Question } from "../../types/Item";
import { toast } from "react-toastify";
import useSetPageTitle from "../../Hooks/useSetPageTitle";
import { useGetAllUnit } from "../../api/unit";
import { useGetAllLesson } from "../../api/lesson";

const EditPage: React.FC = () => {
  const { question_id, subject_id, unit_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({
      questionParentId: question_id,
      onlyWithNoParents: false,
    });

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

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

  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(`PageTitle.unit`) +
      "/" +
      `${unitName}` +
      "/" +
      t(`PageTitle.lesson`) +
      "/" +
      `${lessonName}` +
      "/" +
      t(`PageTitle.questions`),
  );

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

    if (isBseQuestion) {
      const UpdateBseQuestion = {
        id: DataToSend?.id,
        content: DataToSend?.content,
        image: DataToSend?.image ?? "",
      };
      if (
        typeof UpdateBseQuestion?.image === "string" &&
        UpdateBseQuestion?.image !== ""
      ) {
        delete UpdateBseQuestion["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 = ["image", "answer_image"];
          const updatedObject = removeStringKeys(itemToSend, keysToRemove);
          console.log(updatedObject, "updatedObject");

          const tags = processTags(updatedObject);
          const oldQuestionOptions = [] as any;
          const newQuestionOptions = [] as any;

          updatedObject?.QuestionOptions?.forEach((item: any) => {
            if (item?.id) {
              oldQuestionOptions.push(item);
            } else {
              newQuestionOptions.push(item);
            }
          });
          const QuestionOptions = {
            old: oldQuestionOptions,
            new: newQuestionOptions,
          };
          console.log(QuestionOptions);

          mutate({
            ...updatedObject,
            QuestionOptions,
            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 = ["image", "answer_image"];
      const updatedObject = removeStringKeys(DataToSend, keysToRemove);
      delete updatedObject["parent_id"];
      const tags = processTags(updatedObject);
      console.log(updatedObject, "updatedObject");
      if (!updatedObject?.image) {
        updatedObject["image"] = "";
      }
      console.log(updatedObject);

      const oldQuestionOptions = [] as any;
      const newQuestionOptions = [] as any;

      updatedObject?.QuestionOptions?.forEach((item: any) => {
        if (item?.id) {
          // if(!item?.answer_image){
          //   item["answer_image"] = ""
          // }
          console.log(item);

          oldQuestionOptions.push(item);
        } else {
          newQuestionOptions.push(item);
        }
      });

      const QuestionOptions = {
        old: oldQuestionOptions,
        new: newQuestionOptions,
      };
      console.log(QuestionOptions, "QuestionOptions");

      mutate({ ...updatedObject, QuestionOptions, 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>
          <Form />
          <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;
