
import { useEffect, useState } from 'react';
import { io, Socket } from 'socket.io-client';
import { GameState, Player } 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<any[]>([]);

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

        socketInstance.on('connect', () => {
            console.log('Conectado al servidor');
            setIsConnected(true);
        });

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

        socketInstance.on('game_state', (newState: GameState) => {
            console.log('Nuevo estado del juego:', newState);
            setGameState(newState);
        });

        socketInstance.on('rooms_list', (rooms: any[]) => {
            console.log('Lista de salas actualizada:', rooms);
            setRoomsList(rooms);
        });

        // Manejar propio unirse a partida
        socketInstance.on('game_joined', ({ roomId, state }) => {
            setGameState(state);
            // Podríamos guardar el roomId en localStorage o similar si quisiéramos persistencia
        });

        socketInstance.on('error', (msg: string) => {
            alert(msg); // Simple error handling for now
        });

        setSocket(socketInstance);

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

    // Funciones helper para enviar acciones
    const createGame = (hostName: string, maxPlayers: number, password?: string) => {
        socket?.emit('create_game', { hostName, maxPlayers, password });
    };

    const joinGame = (roomId: string, playerName: string, password?: string) => {
        socket?.emit('join_game', { roomId, playerName, password });
    };

    const refreshRooms = () => {
        socket?.emit('get_rooms');
    };

    const startGame = () => {
        socket?.emit('start_game', { roomId: gameState?.roomId });
    };

    const proposeTeam = (teamIds: string[]) => {
        socket?.emit('propose_team', { roomId: gameState?.roomId, teamIds });
    };

    const voteTeam = (approve: boolean) => {
        socket?.emit('vote_team', { roomId: gameState?.roomId, approve });
    };

    const voteMission = (success: boolean) => {
        socket?.emit('vote_mission', { roomId: gameState?.roomId, success });
    };

    const assassinKill = (targetId: string) => {
        socket?.emit('assassin_kill', { roomId: gameState?.roomId, targetId });
    };

    return {
        socket,
        isConnected,
        gameState,
        roomsList,
        actions: {
            createGame,
            joinGame,
            refreshRooms,
            startGame,
            proposeTeam,
            voteTeam,
            voteMission,
            voteLeader: (approve: boolean | null) => socket?.emit('vote_leader', { roomId: gameState?.roomId, approve }),
            assassinKill,
            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 })
        }
    };
};
