import { devlog } from "@frontend/kitui";
import { QuizQuestionResult } from "@frontend/squzanswerer";
import { clearRuleForAll, getQuestionByContentId, updateQuestion } from "@root/questions/actions";
import { useQuestionsStore } from "@root/questions/store";
import { updateRootContentId } from "@root/quizes/actions";
import { useCurrentQuiz } from "@root/quizes/hooks";
import type { CollectionReturnValue, Core } from "cytoscape";
import type { MutableRefObject } from "react";
import { clearDataAfterRemoveNode } from "../helper";

type UseRemoveNodeArgs = {
  cyRef: MutableRefObject<Core | null>;
};

export const useRemoveNode = ({ cyRef }: UseRemoveNodeArgs) => {
  const { questions: trashQuestions } = useQuestionsStore();
  const quiz = useCurrentQuiz();

  const removeNode = (targetNodeContentId: string) => {
    const deleteNodes: string[] = [];
    const cy = cyRef?.current;

    const deleteNodesRecursively = (node: CollectionReturnValue) => {
      //Узнаём грани, идущие от этой ноды
      cy
        ?.$('edge[source = "' + node.id() + '"]')
        ?.toArray()
        .forEach((edge) => {
          const edgeData = edge.data();

          //ищем ноду на конце грани, записываем её ID для дальнейшего удаления
          const targetNode = cy?.$("#" + edgeData.target);
          deleteNodes.push(targetNode.data().id);
          //вызываем функцию для анализа потомков уже у этой ноды
          deleteNodesRecursively(targetNode);
        });
    };

    const elementToDelete = cy?.getElementById(targetNodeContentId);

    if (elementToDelete) {
      deleteNodesRecursively(elementToDelete);
    }

    const targetQuestion = getQuestionByContentId(targetNodeContentId);

    if (targetQuestion?.type && targetQuestion.content.rule.parentId === "root" && quiz) {
      updateRootContentId(quiz.id, "");
      updateQuestion(targetNodeContentId, (question) => {
        question.content.rule.parentId = "";
        question.content.rule.main = [];
        question.content.rule.children = [];
        question.content.rule.default = "";
      });
      clearRuleForAll();
    } else {
      const parentQuestionContentId = cy
        ?.$('edge[target = "' + targetNodeContentId + '"]')
        ?.toArray()?.[0]
        ?.data()?.source;
      if (targetNodeContentId && parentQuestionContentId) {
        if (quiz && cy?.edges(`[source="${parentQuestionContentId}"]`).length === 0) {
          devlog(parentQuestionContentId);
          //createFrontResult(quiz.backendId, parentQuestionContentId);
        }
        clearDataAfterRemoveNode({
          trashQuestions,
          targetQuestionContentId: targetNodeContentId,
          parentQuestionContentId,
        });
      }
    }

    //После всех манипуляций удаляем грани и ноды из CS Чистим rule потомков на беке

    deleteNodes.forEach((nodeId) => {
      //Ноды
      updateQuestion(nodeId, (question) => {
        question.content.rule.parentId = "";
        question.content.rule.main = [];
        question.content.rule.default = "";
        question.content.rule.children = [];
      });
    });

    //делаем result всех потомков неактивными
    trashQuestions.forEach((qr) => {
      if (
        qr.type === "result" &&
        (deleteNodes.includes(qr.content.rule.parentId || "") ||
          (targetQuestion?.type && qr.content.rule.parentId === targetQuestion.content.id))
      ) {
        updateQuestion<QuizQuestionResult>(qr.content.id, (q) => {
          q.content.usage = false;
        });
      }
    });
  };

  return { removeNode };
};
