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

interface Props {
    setOpenedModalQuestions: (open: boolean) => void;
    modalQuestionTargetContentId: string;
}
export const FirstNodeField = ({ setOpenedModalQuestions, modalQuestionTargetContentId }: Props) => {
    const { dragQuestionContentId } = useQuestionsStore()
    const Container = useRef<HTMLDivElement | null>(null);
    const quiz = useCurrentQuiz();
    console.log(dragQuestionContentId)

    const modalOpen = () => setOpenedModalQuestions(true)

    const newRootNode = () => {
        if (quiz) {
            console.log(dragQuestionContentId)

            if (dragQuestionContentId) {
                updateRootInfo(quiz?.id, true)
                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) {
                updateRootInfo(quiz?.id, true)
                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>
    )
}