import {createContext, useEffect, useMemo, useRef, useState} from "react";
import {io} from "socket.io-client";
import useUser from "@/lib/app/hooks/useUser";
import {useTranslations} from "next-intl";
import {toast} from "react-toastify";
import PowerIcon from "@mui/icons-material/Power";
import PowerOffIcon from "@mui/icons-material/PowerOff";
import useDirection from "@/lib/app/hooks/useDirection";

export const SocketContext = createContext()

export const SocketProvider = ({children}) => {
    const {user, isAuth} = useUser()
    const [connectionError, setConnectionError] = useState(false)
    const socketToastId = useRef(null);
    const t = useTranslations()
    const {directionApp} = useDirection();
    const socket = useMemo(() => io(process.env.NEXT_PUBLIC_SERVER_SOCKET_URL, {
        autoConnect: false,
        // transports: ['websocket'],
        auth: {
            token: ""
        }
    }), [])

    useEffect(() => {
        if (isAuth) {
            socket.auth.token = user.telephone_id
            return
        }
        socket.auth.token = ''
    }, [isAuth]);

    useEffect(() => {
        const connectErrorHandler = () => {
            setConnectionError(true)
        }
        const connectHandler = () => {
            setConnectionError(false)
        }
        socket.on("connect_error", connectErrorHandler);
        socket.on("connect", connectHandler);

        return () => {
            socket.off("connect_error", connectErrorHandler);
            socket.off("connect", connectHandler);
        }
    }, []);

    useEffect(() => {
        if (!connectionError) {
            toast.update(socketToastId.current, {
                type: toast.TYPE.SUCCESS,
                render: t('socket_is_connect_message'),
                autoClose: 2000,
                closeButton: true,
                closeOnClick: true,
                icon: <PowerIcon/>
            });
            return
        }
        socketToastId.current = toast.warn(t('socket_is_not_connect_message'), {
            containerId: 'connection',
            draggable: false,
            autoClose: false, closeButton: false, closeOnClick: false, icon: <PowerOffIcon/>
        })

    }, [connectionError]);

    return (
        <SocketContext.Provider value={{socket}}>
            {children}
        </SocketContext.Provider>
    )
}