
import { useEffect, useState, useMemo, useCallback } from 'react';
import { io, Socket } from 'socket.io-client';
import { GameState, GameRoom } from '../../../shared/types';

const SOCKET_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:4000';

export const useSocket = () => {
    const [socket, setSocket] = useState<Socket | null>(null);
    const [gameState, setGameState] = useState<GameState | null>(null);
    const [isConnected, setIsConnected] = useState(false);
    const [roomsList, setRoomsList] = useState<GameRoom[]>([]);

    useEffect(() => {
        const socketInstance = io(SOCKET_URL);

        socketInstance.on('connect', () => {
            console.log('[SOCKET] Conectado exitosamente');
            setIsConnected(true);
        });

        socketInstance.on('disconnect', () => {
            console.log('[SOCKET] Desconectado del servidor');
            setIsConnected(false);
        });

        socketInstance.on('game_state', (newState: GameState) => {
            setGameState(newState);
        });

        socketInstance.on('rooms_list', (rooms: GameRoom[]) => {
            setRoomsList(rooms);
        });

        socketInstance.on('game_joined', ({ state }: { roomId: string, state: GameState }) => {
            setGameState(state);
        });

        socketInstance.on('error', (msg: string) => {
            console.error('[SOCKET ERROR]', msg);
            // Evitamos alert() por ser mala práctica en producción y disparar linters
        });

        socketInstance.on('game_finalized', () => {
            setGameState(null);
        });

        socketInstance.on('player_left_game', ({ playerName }: { playerName: string }) => {
            console.log(`[INFO] Agente ${playerName} fuera de combate.`);
        });

        setSocket(socketInstance);

        return () => {
            socketInstance.disconnect();
        };
    }, []);

    const actions = useMemo(() => ({
        createGame: (hostName: string, maxPlayers: number, password?: string) => {
            socket?.emit('create_game', { hostName, maxPlayers, password });
        },
        joinGame: (roomId: string, playerName: string, password?: string) => {
            socket?.emit('join_game', { roomId, playerName, password });
        },
        refreshRooms: () => {
            socket?.emit('get_rooms');
        },
        startGame: () => {
            socket?.emit('start_game', { roomId: gameState?.roomId });
        },
        proposeTeam: (teamIds: string[]) => {
            socket?.emit('propose_team', { roomId: gameState?.roomId, teamIds });
        },
        voteTeam: (approve: boolean) => {
            socket?.emit('vote_team', { roomId: gameState?.roomId, approve });
        },
        voteMission: (success: boolean) => {
            socket?.emit('vote_mission', { roomId: gameState?.roomId, success });
        },
        voteLeader: (approve: boolean) => socket?.emit('vote_leader', { roomId: gameState?.roomId, approve }),
        assassinKill: (targetId: string) => {
            socket?.emit('assassin_kill', { roomId: gameState?.roomId, targetId });
        },
        leaveGame: () => {
            socket?.emit('leave_game', { roomId: gameState?.roomId });
        },
        reconnectSession: (sessionData: { playerName: string; roomId?: string }) => {
            socket?.emit('reconnect_session', sessionData);
        },
        finishIntro: () => socket?.emit('finish_intro', { roomId: gameState?.roomId }),
        finishReveal: () => socket?.emit('finish_reveal', { roomId: gameState?.roomId }),
        finishRollCall: () => socket?.emit('finish_roll_call', { roomId: gameState?.roomId }),
        finishMissionReveal: () => socket?.emit('finish_reveal', { roomId: gameState?.roomId }),
        finishMissionResult: () => socket?.emit('finish_mission_result', { roomId: gameState?.roomId }),
        restartGame: () => socket?.emit('restart_game', { roomId: gameState?.roomId }),
        finalizeGame: () => socket?.emit('finalize_game', { roomId: gameState?.roomId })
    }), [socket, gameState?.roomId]);

    return {
        socket,
        isConnected,
        gameState,
        roomsList,
        actions
    };
};
