import { Box } from "@mui/material";
import {
  clearRuleForAll,
  createResult,
  updateQuestion,
} from "@root/questions/actions";
import { updateRootContentId } from "@root/quizes/actions";
import { useCurrentQuiz } from "@root/quizes/hooks";
import { useQuizStore } from "@root/quizes/store";
import {
  setOpenedModalQuestions,
  updateOpenedModalSettingsId,
} from "@root/uiTools/actions";
import { useUiTools } from "@root/uiTools/store";
import { enqueueSnackbar } from "notistack";
import { useEffect, useLayoutEffect, useRef } from "react";

export const FirstNodeField = () => {
  const quiz = useCurrentQuiz();
  const modalQuestionTargetContentId = useUiTools(
    (state) => state.modalQuestionTargetContentId,
  );

  useLayoutEffect(() => {
    if (!quiz) return;

    updateOpenedModalSettingsId();
    updateRootContentId(quiz.id, "");
    clearRuleForAll();
  }, []);

  const { dragQuestionContentId } = useUiTools();
  const Container = useRef<HTMLDivElement | null>(null);

  const modalOpen = () => setOpenedModalQuestions(true);

  const newRootNode = () => {
    if (quiz) {
      if (dragQuestionContentId) {
        updateRootContentId(quiz?.id, dragQuestionContentId);
        updateQuestion(
          dragQuestionContentId,
          (question) => (question.content.rule.parentId = "root"),
        );
        createResult(useQuizStore.getState().editQuizId, dragQuestionContentId);
      }
    } else {
      enqueueSnackbar("Нет информации о взятом опроснике");
    }
  };

  useEffect(() => {
    Container.current?.addEventListener("pointerup", newRootNode);
    Container.current?.addEventListener("click", modalOpen);
    return () => {
      Container.current?.removeEventListener("pointerup", newRootNode);
      Container.current?.removeEventListener("click", modalOpen);
    };
  }, [dragQuestionContentId]);

  useEffect(() => {
    if (quiz) {
      if (modalQuestionTargetContentId) {
        updateRootContentId(quiz?.id, modalQuestionTargetContentId);
        updateQuestion(
          modalQuestionTargetContentId,
          (question) => (question.content.rule.parentId = "root"),
        );
        createResult(
          useQuizStore.getState().editQuizId,
          modalQuestionTargetContentId,
        );
      }
    } else {
      enqueueSnackbar("Нет информации о взятом опроснике");
    }
  }, [modalQuestionTargetContentId]);

  return (
    <Box
      ref={Container}
      sx={{
        height: "100%",
        width: "100%",
        backgroundColor: "#f2f3f7",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        color: "#4d4d4d",
        fontSize: "50px",
      }}
    >
      +
    </Box>
  );
};
