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

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

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

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

  const [t] = useTranslation();
  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.edit"),
  );

  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 oldanswers = [] as any;
          const newanswers = [] as any;

          updatedObject?.answers?.forEach((item: any) => {
            if (item?.id) {
              oldanswers.push(item);
            } else {
              newanswers.push(item);
            }
          });
          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 = ["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 oldanswers = [] as any;
      const newanswers = [] as any;

      updatedObject?.answers?.forEach((item: any) => {
        if (item?.id) {
          console.log(item);

          oldanswers.push(item);
        } else {
          newanswers.push(item);
        }
      });

      const answers = {
        old: oldanswers,
        new: newanswers,
      };
      console.log(answers, "answers");

      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;
