'use client';

import { useState, useEffect, useCallback } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { useSocket } from '../../hooks/useSocket';
import { Shield, Users, Gamepad2, LogOut, Clock, History, UserMinus, Key, LucideIcon } from 'lucide-react';

const ADMIN_PASSWORD = "admin123";

interface AdminPlayerData {
    id: string;
    name: string;
}

interface AdminGameData {
    id: string;
    name: string;
    status: string;
    currentPlayers: number;
    maxPlayers: number;
    players: AdminPlayerData[];
}

interface GameHistoryEntry {
    id: number;
    room_name: string;
    host_name: string;
    players: string;
    winner: string | null;
    created_at: string;
}

interface StatItem {
    label: string;
    value: string | number;
    color: string;
    icon: LucideIcon;
}

export default function Dashboard() {
    const { socket, isConnected } = useSocket();
    const [password, setPassword] = useState('');
    const [isAuthenticated, setIsAuthenticated] = useState(false);
    const [activeGames, setActiveGames] = useState<AdminGameData[]>([]);
    const [gameHistory, setGameHistory] = useState<GameHistoryEntry[]>([]);
    const [error, setError] = useState('');

    useEffect(() => {
        const savedSession = typeof window !== 'undefined' ? localStorage.getItem('resistencia_admin_session') : null;
        if (savedSession === 'active') {
            setIsAuthenticated(true);
        }
    }, []);

    useEffect(() => {
        if (isAuthenticated && socket) {
            socket.emit('admin_get_data');

            const handleAdminData = (data: { activeGames: AdminGameData[], history: GameHistoryEntry[] }) => {
                setActiveGames(data.activeGames);
                setGameHistory(data.history);
            };

            const handleSuccess = () => {
                socket.emit('admin_get_data');
            };

            socket.on('admin_data', handleAdminData);
            socket.on('admin_action_success', handleSuccess);

            return () => {
                socket.off('admin_data', handleAdminData);
                socket.off('admin_action_success', handleSuccess);
            };
        }
    }, [isAuthenticated, socket]);

    const handleLogin = (e: React.FormEvent) => {
        e.preventDefault();
        if (password === ADMIN_PASSWORD) {
            setIsAuthenticated(true);
            localStorage.setItem('resistencia_admin_session', 'active');
            setError('');
        } else {
            setError('Acceso Denegado: Contraseña incorrecta');
        }
    };

    const handleLogout = useCallback(() => {
        localStorage.removeItem('resistencia_admin_session');
        setIsAuthenticated(false);
        setPassword('');
    }, []);

    const closeGame = (roomId: string) => {
        if (typeof window !== 'undefined' && window.confirm('¿Seguro que quieres forzar el cierre de esta partida?')) {
            socket?.emit('admin_close_game', { roomId });
        }
    };

    const kickPlayer = (roomId: string, socketId: string) => {
        if (typeof window !== 'undefined' && window.confirm('¿Seguro que quieres expulsar a este jugador?')) {
            socket?.emit('admin_kick_player', { roomId, targetSocketId: socketId });
        }
    };

    const stats: StatItem[] = [
        { label: 'Partidas Activas', value: activeGames.length, color: 'text-red-500', icon: Gamepad2 },
        { label: 'Agentes Online', value: activeGames.reduce((acc, g) => acc + g.currentPlayers, 0), color: 'text-blue-400', icon: Users },
        { label: 'Misiones Registradas', value: gameHistory.length, color: 'text-orange-400', icon: History },
        { label: 'Estado', value: isConnected ? '100%' : '0%', color: 'text-green-400', icon: Clock }
    ];

    if (!isAuthenticated) {
        return (
            <div className="min-h-screen bg-[#0a0a0c] flex items-center justify-center p-4 font-['Inter',sans-serif]">
                <motion.div
                    initial={{ opacity: 0, scale: 0.95 }}
                    animate={{ opacity: 1, scale: 1 }}
                    className="bg-[#121216] border border-white/10 p-10 rounded-3xl w-full max-w-md shadow-[0_20px_50px_rgba(0,0,0,0.5)] relative overflow-hidden"
                >
                    <div className="absolute top-0 left-0 w-full h-1 bg-gradient-to-r from-red-600 via-zinc-800 to-red-600"></div>

                    <div className="flex justify-center mb-8 relative">
                        <div className="absolute inset-0 bg-red-500/20 blur-2xl rounded-full"></div>
                        <Shield size={64} className="text-red-500 relative z-10" />
                    </div>

                    <h1 className="text-3xl font-black text-white text-center mb-2 uppercase tracking-tight">Acceso Admin</h1>
                    <p className="text-gray-400 text-center text-sm mb-10 font-medium">Panel de Control de La Resistencia</p>

                    <form onSubmit={handleLogin} className="space-y-6">
                        <div className="relative">
                            <Key size={18} className="absolute left-4 top-1/2 -translate-y-1/2 text-gray-500" />
                            <input
                                type="password"
                                autoFocus
                                value={password}
                                onChange={(e) => setPassword(e.target.value)}
                                placeholder="Introduce la contraseña"
                                className="w-full bg-[#1a1a20] border border-white/5 rounded-2xl pl-12 pr-6 py-4 text-white focus:outline-none focus:ring-2 focus:ring-red-600/50 transition-all placeholder:text-gray-600 font-medium"
                            />
                        </div>

                        {error && (
                            <motion.p
                                initial={{ opacity: 0, y: -10 }}
                                animate={{ opacity: 1, y: 0 }}
                                className="text-red-500 text-xs font-bold text-center mt-2 flex items-center justify-center gap-2"
                            >
                                <span className="w-1.5 h-1.5 bg-red-500 rounded-full animate-pulse"></span>
                                {error}
                            </motion.p>
                        )}

                        <button
                            type="submit"
                            className="w-full bg-red-600 hover:bg-red-500 text-white font-black py-4 rounded-2xl shadow-xl shadow-red-600/10 transition-all uppercase tracking-[0.2em] text-xs hover:scale-[1.02] active:scale-[0.98]"
                        >
                            Entrar en Sistema
                        </button>
                    </form>
                </motion.div>
            </div>
        );
    }

    return (
        <div className="min-h-screen bg-[#0a0a0c] text-white p-4 md:p-10 font-['Inter',sans-serif]">
            {/* Header */}
            <header className="max-w-7xl mx-auto flex flex-col md:flex-row justify-between items-start md:items-center mb-12 gap-6">
                <div className="space-y-1">
                    <div className="flex items-center gap-3 text-red-500">
                        <div className="p-2 bg-red-500/10 rounded-lg">
                            <Shield size={22} />
                        </div>
                        <span className="text-[10px] font-black uppercase tracking-[0.4em] opacity-80">Seguimiento de Operaciones</span>
                    </div>
                    <h1 className="text-5xl font-black tracking-tighter uppercase italic text-transparent bg-clip-text bg-gradient-to-r from-white via-white to-gray-500">Comandante</h1>
                </div>

                <div className="flex items-center gap-6 bg-[#121216] border border-white/10 px-8 py-4 rounded-3xl shadow-xl">
                    <div className="flex flex-col items-end">
                        <span className="text-[10px] text-gray-500 uppercase font-black tracking-widest mb-1">Status Servidor</span>
                        <div className="flex items-center gap-2">
                            <div className={`w-2.5 h-2.5 rounded-full ${isConnected ? 'bg-green-500 shadow-[0_0_15px_rgba(34,197,94,0.6)] animate-pulse' : 'bg-red-500'}`}></div>
                            <span className="text-xs font-mono font-black tracking-widest">{isConnected ? 'OPERATIVO' : 'DESCONECTADO'}</span>
                        </div>
                    </div>

                    <div className="w-px h-8 bg-white/10 mx-2"></div>

                    <button
                        onClick={handleLogout}
                        className="flex items-center gap-2 px-5 py-2.5 bg-zinc-800 hover:bg-red-600 text-gray-300 hover:text-white rounded-xl transition-all font-black text-[10px] uppercase tracking-widest group"
                    >
                        <LogOut size={16} className="group-hover:translate-x-1 transition-transform" />
                        Desconectar
                    </button>
                </div>
            </header>

            <main className="max-w-7xl mx-auto grid grid-cols-1 lg:grid-cols-12 gap-10">

                {/* Panel Latino: Estadísticas Rápidas */}
                <div className="lg:col-span-12 grid grid-cols-2 md:grid-cols-4 gap-4 mb-2">
                    {stats.map((stat, i) => {
                        const Icon = stat.icon;
                        return (
                            <div key={i} className="bg-[#121216] border border-white/5 p-6 rounded-2xl flex items-center justify-between">
                                <div>
                                    <p className="text-[10px] uppercase font-black tracking-widest text-gray-500 mb-1">{stat.label}</p>
                                    <p className={`text-2xl font-black ${stat.color}`}>{stat.value}</p>
                                </div>
                                <Icon className="opacity-10" size={32} />
                            </div>
                        );
                    })}
                </div>

                {/* Columna Principal: Partidas Activas */}
                <div className="lg:col-span-8 space-y-8">
                    <section>
                        <div className="flex items-center gap-4 mb-8">
                            <h2 className="text-xl font-black text-white uppercase tracking-tighter italic border-l-4 border-red-600 pl-4">Canales de Radio Activos</h2>
                        </div>

                        <div className="grid gap-6">
                            <AnimatePresence mode="popLayout">
                                {activeGames.length === 0 ? (
                                    <motion.div
                                        initial={{ opacity: 0 }}
                                        animate={{ opacity: 1 }}
                                        key="empty-state"
                                        className="bg-[#121216]/40 border border-dashed border-white/10 rounded-3xl p-20 text-center"
                                    >
                                        <Clock size={48} className="mx-auto mb-6 text-gray-700" />
                                        <p className="text-lg font-bold text-gray-600 uppercase tracking-widest">Silencio Radioeléctrico</p>
                                        <p className="text-xs text-gray-700 font-medium">Buscando señales de misiones activas...</p>
                                    </motion.div>
                                ) : (
                                    activeGames.map((game) => (
                                        <motion.div
                                            key={game.id}
                                            layout
                                            initial={{ opacity: 0, x: -20 }}
                                            animate={{ opacity: 1, x: 0 }}
                                            exit={{ opacity: 0, scale: 0.95 }}
                                            className="bg-[#121216] border border-white/10 rounded-3xl p-8 hover:bg-[#16161c] transition-all group shadow-xl"
                                        >
                                            <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-6">
                                                <div className="flex-1">
                                                    <div className="flex items-center gap-3 mb-2">
                                                        <h3 className="text-2xl font-black text-white italic uppercase tracking-tighter leading-none">{game.name}</h3>
                                                        <span className="text-[10px] font-bold px-2 py-0.5 bg-red-500/10 text-red-500 rounded border border-red-500/20">{game.status}</span>
                                                    </div>
                                                    <div className="flex items-center gap-4 text-[10px] uppercase font-black tracking-widest text-gray-500">
                                                        <span className="flex items-center gap-1.5">
                                                            <Users size={12} className="text-red-500" />
                                                            {game.currentPlayers} / {game.maxPlayers} Agentes Movilizados
                                                        </span>
                                                        <span className="text-gray-800">|</span>
                                                        <span>ID: {game.id.slice(0, 8)}</span>
                                                    </div>
                                                </div>

                                                <button
                                                    onClick={() => closeGame(game.id)}
                                                    className="px-6 py-3 bg-zinc-900 hover:bg-red-600 text-gray-400 hover:text-white rounded-2xl text-[10px] font-black uppercase tracking-[0.2em] transition-all border border-white/5 active:scale-95 whitespace-nowrap"
                                                >
                                                    Abortar Misión
                                                </button>
                                            </div>

                                            {/* Subpanel: Jugadores */}
                                            <div className="mt-8 pt-8 border-t border-white/5">
                                                <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-4">
                                                    {game.players.map((player) => (
                                                        <div key={player.id} className="bg-black/40 p-4 rounded-2xl border border-white/5 flex items-center justify-between group/player hover:border-red-500/30 transition-all">
                                                            <div className="flex items-center gap-3">
                                                                <div className="w-10 h-10 rounded-xl bg-white/5 flex items-center justify-center font-black text-red-500 border border-white/5 group-hover/player:bg-red-500 group-hover/player:text-white transition-all">
                                                                    {player.name[0].toUpperCase()}
                                                                </div>
                                                                <div>
                                                                    <p className="text-sm font-black text-white leading-none mb-1">{player.name}</p>
                                                                    <p className="text-[9px] opacity-30 font-mono italic">AG-{player.id.slice(0, 4)}</p>
                                                                </div>
                                                            </div>
                                                            <button
                                                                onClick={() => kickPlayer(game.id, player.id)}
                                                                className="p-2.5 text-gray-700 hover:text-red-500 hover:bg-red-500/10 rounded-xl transition-all opacity-0 group-hover/player:opacity-100"
                                                                title="Expulsar de la zona"
                                                            >
                                                                <UserMinus size={18} />
                                                            </button>
                                                        </div>
                                                    ))}
                                                </div>
                                            </div>
                                        </motion.div>
                                    ))
                                )}
                            </AnimatePresence>
                        </div>
                    </section>
                </div>

                {/* Columna Lateral: Archivo Histórico */}
                <div className="lg:col-span-4 space-y-8">
                    <section className="sticky top-10">
                        <div className="flex items-center gap-4 mb-8">
                            <h2 className="text-xl font-black text-white uppercase tracking-tighter italic border-l-4 border-gray-600 pl-4">Informe Forense</h2>
                        </div>

                        <div className="bg-[#121216] border border-white/10 rounded-3xl overflow-hidden shadow-2xl">
                            <div className="p-6 bg-white/5 border-b border-white/5">
                                <p className="text-[10px] uppercase font-black tracking-widest text-gray-400">Últimos Informes Desclasificados</p>
                            </div>

                            <div className="max-h-[60vh] overflow-y-auto custom-scrollbar p-6 space-y-6">
                                {gameHistory.length === 0 ? (
                                    <div className="text-center py-20 opacity-10">
                                        <History size={40} className="mx-auto mb-4" />
                                        <p className="text-xs italic font-bold">Sin archivos registrados</p>
                                    </div>
                                ) : (
                                    gameHistory.map((entry) => (
                                        <motion.div
                                            initial={{ opacity: 0 }}
                                            animate={{ opacity: 1 }}
                                            key={entry.id}
                                            className="group relative"
                                        >
                                            <div className="flex justify-between items-start">
                                                <div className="space-y-1">
                                                    <h4 className="text-sm font-black text-gray-200 uppercase tracking-tight group-hover:text-white transition-colors leading-none mb-1">{entry.room_name}</h4>
                                                    <div className="flex items-center gap-2 text-[9px] text-gray-600 font-bold uppercase tracking-widest">
                                                        <span>{entry.host_name}</span>
                                                        <span>•</span>
                                                        <span>{new Date(entry.created_at).toLocaleDateString()}</span>
                                                    </div>
                                                </div>
                                                <div className={`text-[9px] font-black uppercase px-2 py-1 rounded shadow-sm ${entry.winner === 'resistance' ? 'bg-green-500/20 text-green-500' :
                                                        entry.winner === 'spies' ? 'bg-red-500/20 text-red-500' : 'bg-gray-700/20 text-gray-500'
                                                    }`}>
                                                    {entry.winner ? (entry.winner === 'resistance' ? 'RES' : 'SPIES') : 'LOGOUT'}
                                                </div>
                                            </div>
                                            <div className="mt-2 flex items-center gap-3 text-[9px] opacity-40 group-hover:opacity-60 transition-opacity">
                                                <span className="flex items-center gap-1 font-mono">{entry.players.split(',').length} Agtes</span>
                                                <div className="w-1 h-1 bg-white/20 rounded-full"></div>
                                                <span>{new Date(entry.created_at).toLocaleTimeString()}</span>
                                            </div>
                                            <div className="absolute -left-6 top-1.5 w-1 h-0 group-hover:h-3 bg-red-600 transition-all rounded-full"></div>
                                        </motion.div>
                                    ))
                                )}
                            </div>

                            <div className="p-6 bg-white/5 border-t border-white/5">
                                <p className="text-[9px] font-bold text-center text-gray-600 uppercase tracking-widest">Fin del Informe Forense</p>
                            </div>
                        </div>
                    </section>
                </div>
            </main>

            <style jsx global>{`
                @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;700;900&display=swap');
                
                body {
                    background-color: #0a0a0c;
                    cursor: crosshair;
                }

                .custom-scrollbar::-webkit-scrollbar {
                    width: 3px;
                }
                .custom-scrollbar::-webkit-scrollbar-track {
                    background: transparent;
                }
                .custom-scrollbar::-webkit-scrollbar-thumb {
                    background: rgba(255, 255, 255, 0.05);
                    border-radius: 10px;
                }
                .custom-scrollbar::-webkit-scrollbar-thumb:hover {
                    background: rgba(255, 255, 255, 0.1);
                }
            `}</style>
        </div>
    );
}
