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

interface Props {
    setOpenedModalQuestions: (open: boolean) => void;
    modalQuestionTargetContentId: string;
}
export const FirstNodeField = ({ setOpenedModalQuestions, modalQuestionTargetContentId }: Props) => {
    const quiz = useCurrentQuiz();


    useLayoutEffect(() => {
    console.log("компонент с плюсом")
        updateOpenedModalSettingsId()
           updateRootContentId(quiz.id, "")
           clearRuleForAll()
      }, [])


    const { questions } = useQuestionsStore()
    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(quiz?.backendId, dragQuestionContentId)
            }
        } else {
            enqueueSnackbar("Нет информации о взятом опроснике")
        }

    }

    useEffect(() => {
        Container.current?.addEventListener("mouseup", newRootNode)
        Container.current?.addEventListener("click", modalOpen)
        return () => { 
            Container.current?.removeEventListener("mouseup", 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(quiz?.backendId, 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>
    )
}
