import React, { createContext, useContext, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { listenToGameUpdates } from '@/firebase/game';

const GameStateContext = createContext<string | null>(null);

export function GameStateProvider({ children, gameId }: { children: React.ReactNode, gameId: string | null }) {
    const navigate = useNavigate();

    useEffect(() => {
        console.log("GameStateProvider: useEffect triggered. gameId:", gameId);
        
        if (!gameId) {
            console.log("GameStateProvider: No gameId provided, returning early");
            return;
        }

        console.log("GameStateProvider: Setting up listener for game updates");
        const unsubscribe = listenToGameUpdates(gameId, (gameData) => {
            console.log("GameStateProvider: Received game update", gameData);
            
            if (!gameData || !gameData.state) {
                console.log("GameStateProvider: Invalid game data received", gameData);
                return;
            }

            console.log("GameStateProvider: Navigating to", gameData.state);
            switch (gameData.state) {
                case 'lobby':
                    navigate(`/lobby/${gameId}`);
                    break;
                case 'round_start':
                    navigate(`/challenge/${gameId}`);
                    break;
                case 'song_submission':
                    navigate(`/song-selection/${gameId}`);
                    break;
                case 'music_playback':
                    navigate(`/playback/${gameId}`);
                    break;
                case 'ranking':
                    navigate(`/ranking/${gameId}`);
                    break;
                case 'scoreboard':
                    navigate(`/scoreboard/${gameId}`);
                    break;
                case 'game_end':
                    navigate(`/game-over/${gameId}`);
                    break;
                default:
                    console.log('GameStateProvider: No navigation for this state', gameData.state);
                    break;
            }
        });

        return () => {
            console.log("GameStateProvider: Cleaning up listener");
            unsubscribe();
        };
    }, [gameId]);

    console.log("GameStateProvider: Rendering with gameId:", gameId);
    return <GameStateContext.Provider value={gameId}>{children}</GameStateContext.Provider>;
}

export function useGameState() {
    return useContext(GameStateContext);
}

export const listenToGameUpdates = (gameId: string, callback: (game: any) => void): (() => void) => {
    console.log("listenToGameUpdates: Setting up listener for gameId:", gameId);
    
    const gameRef = doc(db, 'games', gameId);
    return onSnapshot(gameRef, 
        (docSnap) => {
            if (docSnap.exists()) {
                const gameData = { id: docSnap.id, ...docSnap.data() };
                console.log("listenToGameUpdates: Received update", gameData);
                callback(gameData);
            } else {
                console.log("listenToGameUpdates: No such document!");
            }
        },
        (error) => {
            console.error("listenToGameUpdates: Error fetching document:", error);
        }
    );
};

do you see a bug?