import { Box } from "@mui/material"
import { useEffect, useRef, useState } from "react";
import { updateDragQuestionContentId, updateQuestion } from "@root/questions/actions"
import { updateRootContentId } from "@root/quizes/actions"
import { useCurrentQuiz } from "@root/quizes/hooks"
import { useQuestionsStore } from "@root/questions/store"
import { enqueueSnackbar } from "notistack";

interface Props {
    setOpenedModalQuestions: (open: boolean) => void;
    modalQuestionTargetContentId: string;
}
export const FirstNodeField = ({ setOpenedModalQuestions, modalQuestionTargetContentId }: Props) => {
    const quiz = useCurrentQuiz();
    const { dragQuestionContentId, questions } = useQuestionsStore()
    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")
            }
        } 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")
            }
        } 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>
    )
}