import { useEffect, useRef } from "react";
import { ConnectionState } from "~/lib/websocket/voice/types";
import { useGatewayStore } from "~/stores/gateway-store";
import { useVoiceStateStore } from "~/stores/voice-state-store";
import { useWebRTCStore } from "~/stores/webrtc-store";

export function WebRTCConnectionManager() {
    const gateway = useGatewayStore();
    const voiceState = useVoiceStateStore();
    const webrtc = useWebRTCStore();

    const remoteStream = useWebRTCStore((state) => state.remoteStream);
    const audioRef = useRef<HTMLAudioElement>(null);

    if (audioRef.current) {
        audioRef.current.srcObject = remoteStream;
    }

    useEffect(() => {
        const unsubscribe = gateway.onVoiceServerUpdate(async (event) => {
            await webrtc.connect(event.token);
            voiceState.joinVoiceChannel(event.serverId, event.channelId);

            const stream = await navigator.mediaDevices.getUserMedia({
                audio: {
                    noiseSuppression: false,
                },
                video: false,
            });

            webrtc.createOffer(stream);
        });

        return () => {
            voiceState.leaveVoiceChannel();
            unsubscribe();
        };
    }, []);

    useEffect(() => {
        if (webrtc.status === ConnectionState.DISCONNECTED) {
            voiceState.leaveVoiceChannel();
        }
    }, [webrtc.status]);

    return (
        <>
            <audio autoPlay ref={audioRef} className="hidden" />
        </>
    );
}
