import {Dialog} from "@mui/material";
import {DialogTransition} from "@/core/components/DialogTransition";
import {useEffect} from "react";
import useCallDialog from "@/lib/callWidget/hooks/useCallDialog";
import useAnswers from "@/lib/callWidget/hooks/useAnswers";
import useSocket from "@/lib/app/hooks/useSocket";
import CallTabs from "@/components/layouts/Dashboard/CallWidget/CallWidgetDialog/CallTabs";

const CallWidgetDialog = () => {
    const {openCallDialog, setOpenCallDialog} = useCallDialog()
    const {answersList, newAnswerTab} = useAnswers()
    const socket = useSocket()

    useEffect(() => {
        const answerCall = (_data, act) => {
            const data = JSON.parse(_data)
            newAnswerTab({
                id: data.call_id,
                phone_number: data.phone_number
            })
            act()
        }
        socket.on('answer', answerCall)

        return () => {
            socket.off('answer', answerCall)
        }
    });

    useEffect(() => {
        if (answersList.length === 0) {
            setOpenCallDialog(false)
            return
        }
        setOpenCallDialog(true)
    }, [answersList.length]);

    return (
        <Dialog
            fullScreen
            open = {openCallDialog}
            TransitionComponent = {DialogTransition}
        >
            <CallTabs/>
        </Dialog>
    )
}

export default CallWidgetDialog