import { ServerInstance } from './ServerList';
import { Activity, ArrowUpRight, Check, Copy, Cpu, Database, HardDrive, Headphones, Layers, Play, RefreshCw, Send, Server, ShieldCheck, Square, Terminal, Wifi, X } from 'lucide-react';
import React, { useEffect, useRef, useState } from 'react';

interface ServerConsoleModalProps {
    server: ServerInstance | null;
    onClose: () => void;
}

export const ServerConsoleModal: React.FC<ServerConsoleModalProps> = ({ server, onClose }) => {
    if (!server) return null;

    const [activeTab, setActiveTab] = useState<'console' | 'metrics' | 'network' | 'backups'>('console');
    const [status, setStatus] = useState<'online' | 'starting' | 'stopping' | 'offline'>(server.status || 'online');
    const [logs, setLogs] = useState<Array<{ time: string; level: 'INFO' | 'WARN' | 'ERROR' | 'JOIN' | 'EXEC'; message: string }>>([
        { time: '11:48:02', level: 'INFO', message: 'Loading Paper server version 1.21-R0.1-SNAPSHOT' },
        { time: '11:48:05', level: 'INFO', message: 'Initializing KVM Direct PCIe passthrough' },
        { time: '11:48:09', level: 'INFO', message: 'Preparing level "world" (Overworld, Nether, End)' },
        { time: '11:48:12', level: 'INFO', message: 'Done (4.12s)! Server listening on 0.0.0.0:25565' },
        { time: '11:50:44', level: 'JOIN', message: 'Player "Steve" joined the game from 178.12.99.12' },
        { time: '11:52:10', level: 'INFO', message: 'Auto-save completed. 1,420 chunks saved.' },
    ]);
    const [commandInput, setCommandInput] = useState('');
    const [copiedIp, setCopiedIp] = useState(false);
    const [cpuVal, setCpuVal] = useState(18);
    const [ramVal, setRamVal] = useState(3.2);

    const logEndRef = useRef<HTMLDivElement>(null);

    useEffect(() => {
        logEndRef.current?.scrollIntoView({ behavior: 'smooth' });
    }, [logs]);

    // Usage fluctuation simulator
    useEffect(() => {
        if (status !== 'online') return;
        const interval = setInterval(() => {
            setCpuVal(Math.floor(Math.random() * 12) + 14);
            setRamVal(parseFloat((Math.random() * 0.3 + 3.1).toFixed(1)));
        }, 3000);
        return () => clearInterval(interval);
    }, [status]);

    const handlePower = (action: 'start' | 'stop' | 'restart') => {
        const timeStr = new Date().toLocaleTimeString('de-DE');
        if (action === 'stop') {
            setStatus('stopping');
            setLogs((prev) => [...prev, { time: timeStr, level: 'WARN', message: 'Stopping server gracefully...' }]);
            setTimeout(() => {
                setStatus('offline');
                setCpuVal(0);
                setRamVal(0);
                setLogs((prev) => [...prev, { time: timeStr, level: 'INFO', message: 'Server process terminated. Offline.' }]);
            }, 1200);
        } else if (action === 'start') {
            setStatus('starting');
            setLogs((prev) => [...prev, { time: timeStr, level: 'INFO', message: 'Initiating Paper 1.21 boot sequence...' }]);
            setTimeout(() => {
                setStatus('online');
                setCpuVal(18);
                setRamVal(3.2);
                setLogs((prev) => [...prev, { time: timeStr, level: 'INFO', message: 'Server is ONLINE and listening on port 25565.' }]);
            }, 1200);
        } else if (action === 'restart') {
            setStatus('starting');
            setLogs((prev) => [...prev, { time: timeStr, level: 'WARN', message: 'Rebooting server process...' }]);
            setTimeout(() => {
                setStatus('online');
                setCpuVal(16);
                setRamVal(3.2);
                setLogs((prev) => [...prev, { time: timeStr, level: 'INFO', message: 'Reboot complete. All systems nominal.' }]);
            }, 1200);
        }
    };

    const handleSendCommand = (cmdToRun?: string) => {
        const targetCmd = (cmdToRun || commandInput).trim();
        if (!targetCmd) return;

        const timeStr = new Date().toLocaleTimeString('de-DE');
        setLogs((prev) => [...prev, { time: timeStr, level: 'EXEC', message: `> ${targetCmd}` }]);

        // Simulated Command Responses
        setTimeout(() => {
            let resp = `Command "${targetCmd}" executed successfully.`;
            if (targetCmd === '/tps') {
                resp = 'TPS from last 1m, 5m, 15m: 20.0, 20.0, 19.98';
            } else if (targetCmd === '/list') {
                resp = 'There are 4 of 100 players online: Steve, Alex, Notch, Gamer99';
            } else if (targetCmd === '/help') {
                resp = 'Available commands: /tps, /list, /say <msg>, /save-all, /reload, /op <player>';
            } else if (targetCmd.startsWith('/say')) {
                resp = `[Server] ${targetCmd.replace('/say ', '')}`;
            }

            setLogs((prev) => [...prev, { time: timeStr, level: 'INFO', message: resp }]);
        }, 300);

        setCommandInput('');
    };

    const copyIp = () => {
        navigator.clipboard.writeText(server.ip);
        setCopiedIp(true);
        setTimeout(() => setCopiedIp(false), 2000);
    };

    return (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-950/85 backdrop-blur-md animate-fade-in">
            <div className="w-full max-w-4xl rounded-2xl border border-[#1b2a4e] bg-[#0c1224] shadow-2xl shadow-blue-950/60 overflow-hidden flex flex-col max-h-[90vh]">
                {/* Modal Header */}
                <div className="bg-[#090e1c] px-6 py-4 border-b border-[#162242] flex flex-wrap items-center justify-between gap-4">
                    <div className="flex items-center gap-3">
                        <div className="p-2.5 rounded-xl bg-blue-600/20 border border-blue-500/30 text-blue-400">
                            <Server className="h-5 w-5" />
                        </div>
                        <div>
                            <div className="flex items-center gap-2">
                                <h3 className="font-extrabold text-white text-base">{server.name}</h3>
                                <span
                                    className={`px-2.5 py-0.5 rounded-full text-[10px] font-mono font-bold uppercase flex items-center gap-1 border ${
                                        status === 'online'
                                            ? 'bg-emerald-950 text-emerald-400 border-emerald-800'
                                            : status === 'offline'
                                            ? 'bg-red-950 text-red-400 border-red-800'
                                            : 'bg-yellow-950 text-yellow-400 border-yellow-800 animate-pulse'
                                    }`}
                                >
                                    <span
                                        className={`h-1.5 w-1.5 rounded-full ${
                                            status === 'online' ? 'bg-emerald-400 animate-ping' : 'bg-red-400'
                                        }`}
                                    />
                                    {status} (20.0 TPS)
                                </span>
                            </div>

                            <div className="flex items-center gap-3 text-xs text-slate-400 mt-0.5 font-mono">
                                <button
                                    onClick={copyIp}
                                    className="flex items-center gap-1 text-blue-400 hover:underline font-semibold"
                                >
                                    {server.ip}
                                    {copiedIp ? <Check className="h-3 w-3 text-emerald-400" /> : <Copy className="h-3 w-3" />}
                                </button>
                                <span>•</span>
                                <span>{server.location}</span>
                                <span>•</span>
                                <span>{server.vcpu} Cores / {server.ram} GB RAM</span>
                            </div>
                        </div>
                    </div>

                    {/* Power Controls & Close */}
                    <div className="flex items-center gap-2">
                        {status === 'offline' ? (
                            <button
                                onClick={() => handlePower('start')}
                                className="px-3 py-1.5 rounded-xl bg-emerald-600 hover:bg-emerald-500 text-white font-bold text-xs flex items-center gap-1.5 shadow-md"
                            >
                                <Play className="h-3.5 w-3.5 fill-white" /> Start
                            </button>
                        ) : (
                            <>
                                <button
                                    onClick={() => handlePower('restart')}
                                    className="px-3 py-1.5 rounded-xl bg-[#1c2a4e] hover:bg-[#253969] text-amber-300 border border-[#2c4075] font-bold text-xs flex items-center gap-1.5"
                                >
                                    <RefreshCw className="h-3.5 w-3.5" /> Neustart
                                </button>
                                <button
                                    onClick={() => handlePower('stop')}
                                    className="px-3 py-1.5 rounded-xl bg-red-950/80 hover:bg-red-900 text-red-300 border border-red-800/80 font-bold text-xs flex items-center gap-1.5"
                                >
                                    <Square className="h-3.5 w-3.5 fill-red-400" /> Stoppen
                                </button>
                            </>
                        )}
                        <button
                            onClick={onClose}
                            className="p-2 rounded-xl text-slate-400 hover:text-white hover:bg-[#141e3a] transition-colors"
                        >
                            <X className="h-5 w-5" />
                        </button>
                    </div>
                </div>

                {/* Tab Navigation */}
                <div className="bg-[#090e1c] px-6 border-b border-[#162242] flex gap-2 font-medium text-xs">
                    <button
                        onClick={() => setActiveTab('console')}
                        className={`flex items-center gap-2 py-3 px-4 border-b-2 font-semibold transition-all ${
                            activeTab === 'console'
                                ? 'border-blue-500 text-blue-400 bg-[#0d1428]'
                                : 'border-transparent text-slate-400 hover:text-white'
                        }`}
                    >
                        <Terminal className="h-4 w-4" /> Live Konsole
                    </button>
                    <button
                        onClick={() => setActiveTab('metrics')}
                        className={`flex items-center gap-2 py-3 px-4 border-b-2 font-semibold transition-all ${
                            activeTab === 'metrics'
                                ? 'border-blue-500 text-blue-400 bg-[#0d1428]'
                                : 'border-transparent text-slate-400 hover:text-white'
                        }`}
                    >
                        <Activity className="h-4 w-4" /> Auslastung & Metriken
                    </button>
                    <button
                        onClick={() => setActiveTab('network')}
                        className={`flex items-center gap-2 py-3 px-4 border-b-2 font-semibold transition-all ${
                            activeTab === 'network'
                                ? 'border-blue-500 text-blue-400 bg-[#0d1428]'
                                : 'border-transparent text-slate-400 hover:text-white'
                        }`}
                    >
                        <Wifi className="h-4 w-4" /> IP & Netzwerk
                    </button>
                    <button
                        onClick={() => setActiveTab('backups')}
                        className={`flex items-center gap-2 py-3 px-4 border-b-2 font-semibold transition-all ${
                            activeTab === 'backups'
                                ? 'border-blue-500 text-blue-400 bg-[#0d1428]'
                                : 'border-transparent text-slate-400 hover:text-white'
                        }`}
                    >
                        <Database className="h-4 w-4" /> Backups (3)
                    </button>
                </div>

                {/* Modal Body */}
                <div className="p-6 flex-1 overflow-y-auto bg-[#070b14]">
                    {/* TAB 1: LIVE CONSOLE */}
                    {activeTab === 'console' && (
                        <div className="space-y-4">
                            {/* Quick command buttons */}
                            <div className="flex flex-wrap gap-2 text-xs">
                                <span className="text-slate-500 font-mono self-center mr-1 text-[11px]">Quick-Commands:</span>
                                <button
                                    onClick={() => handleSendCommand('/tps')}
                                    className="px-2.5 py-1 rounded-lg bg-[#121c38] border border-[#1e2f5b] text-blue-300 font-mono hover:bg-[#1b2b52]"
                                >
                                    /tps
                                </button>
                                <button
                                    onClick={() => handleSendCommand('/list')}
                                    className="px-2.5 py-1 rounded-lg bg-[#121c38] border border-[#1e2f5b] text-blue-300 font-mono hover:bg-[#1b2b52]"
                                >
                                    /list
                                </button>
                                <button
                                    onClick={() => handleSendCommand('/say Willkommen auf dem Server!')}
                                    className="px-2.5 py-1 rounded-lg bg-[#121c38] border border-[#1e2f5b] text-blue-300 font-mono hover:bg-[#1b2b52]"
                                >
                                    /say Broadcast
                                </button>
                                <button
                                    onClick={() => handleSendCommand('/help')}
                                    className="px-2.5 py-1 rounded-lg bg-[#121c38] border border-[#1e2f5b] text-blue-300 font-mono hover:bg-[#1b2b52]"
                                >
                                    /help
                                </button>
                            </div>

                            {/* Monospace Terminal Logs */}
                            <div className="rounded-xl border border-[#162242] bg-[#050810] p-4 font-mono text-xs space-y-1.5 max-h-[320px] min-h-[260px] overflow-y-auto shadow-inner">
                                {logs.map((log, idx) => (
                                    <div key={idx} className="leading-relaxed flex items-start gap-2">
                                        <span className="text-slate-600 select-none text-[11px]">{log.time}</span>
                                        <span
                                            className={`font-bold px-1.5 py-0.2 rounded text-[10px] ${
                                                log.level === 'EXEC'
                                                    ? 'bg-blue-950 text-blue-400'
                                                    : log.level === 'JOIN'
                                                    ? 'bg-emerald-950 text-emerald-400'
                                                    : log.level === 'WARN'
                                                    ? 'bg-yellow-950 text-yellow-400'
                                                    : 'bg-slate-800 text-slate-300'
                                            }`}
                                        >
                                            {log.level}
                                        </span>
                                        <span
                                            className={
                                                log.level === 'EXEC'
                                                    ? 'text-cyan-300 font-semibold'
                                                    : log.level === 'JOIN'
                                                    ? 'text-emerald-300'
                                                    : 'text-slate-200'
                                            }
                                        >
                                            {log.message}
                                        </span>
                                    </div>
                                ))}
                                <div ref={logEndRef} />
                            </div>

                            {/* Command Input Form */}
                            <form
                                onSubmit={(e) => {
                                    e.preventDefault();
                                    handleSendCommand();
                                }}
                                className="flex gap-2"
                            >
                                <div className="relative flex-1">
                                    <span className="absolute left-3 top-1/2 -translate-y-1/2 font-mono text-xs text-blue-400">
                                        &gt;
                                    </span>
                                    <input
                                        type="text"
                                        value={commandInput}
                                        onChange={(e) => setCommandInput(e.target.value)}
                                        placeholder="Server-Befehl eingeben (z. B. op player, list, say Hi)..."
                                        className="w-full bg-[#0d1428] border border-[#1c2a4f] rounded-xl pl-8 pr-4 py-2.5 text-xs font-mono text-white outline-none focus:border-blue-500"
                                    />
                                </div>
                                <button
                                    type="submit"
                                    className="px-5 py-2.5 rounded-xl bg-[#3b82f6] hover:bg-[#2563eb] text-white font-bold text-xs flex items-center gap-1.5 shadow-md shadow-blue-500/20"
                                >
                                    <Send className="h-3.5 w-3.5" /> Befehl Senden
                                </button>
                            </form>
                        </div>
                    )}

                    {/* TAB 2: METRICS */}
                    {activeTab === 'metrics' && (
                        <div className="space-y-6">
                            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                                {/* CPU */}
                                <div className="rounded-2xl border border-[#192648] bg-[#0d1428] p-5 space-y-3">
                                    <div className="flex justify-between items-center text-xs font-bold">
                                        <span className="text-slate-300 flex items-center gap-2">
                                            <Cpu className="h-4 w-4 text-cyan-400" /> AMD EPYC™ 9004 vCPU
                                        </span>
                                        <span className="font-mono text-cyan-400">{cpuVal}%</span>
                                    </div>
                                    <div className="w-full bg-[#070c18] h-2.5 rounded-full overflow-hidden border border-[#162242]">
                                        <div
                                            className="bg-cyan-400 h-full transition-all duration-500"
                                            style={{ width: `${cpuVal}%` }}
                                        />
                                    </div>
                                    <div className="text-[11px] text-slate-400 font-mono flex justify-between">
                                        <span>4 Cores zugewiesen</span>
                                        <span>0% Throttling</span>
                                    </div>
                                </div>

                                {/* RAM */}
                                <div className="rounded-2xl border border-[#192648] bg-[#0d1428] p-5 space-y-3">
                                    <div className="flex justify-between items-center text-xs font-bold">
                                        <span className="text-slate-300 flex items-center gap-2">
                                            <Layers className="h-4 w-4 text-blue-400" /> DDR5 Registered ECC RAM
                                        </span>
                                        <span className="font-mono text-blue-400">{ramVal} GB / {server.ram} GB</span>
                                    </div>
                                    <div className="w-full bg-[#070c18] h-2.5 rounded-full overflow-hidden border border-[#162242]">
                                        <div
                                            className="bg-blue-400 h-full transition-all duration-500"
                                            style={{ width: `${(ramVal / server.ram) * 100}%` }}
                                        />
                                    </div>
                                    <div className="text-[11px] text-slate-400 font-mono flex justify-between">
                                        <span>Heap Allocated: 4.0 GB</span>
                                        <span>Heap Free: 4.8 GB</span>
                                    </div>
                                </div>
                            </div>

                            {/* Storage & Network */}
                            <div className="rounded-2xl border border-[#192648] bg-[#0d1428] p-5 space-y-4">
                                <h4 className="text-xs font-bold text-white uppercase tracking-wider flex items-center gap-2">
                                    <HardDrive className="h-4 w-4 text-purple-400" /> PCIe Gen4 NVMe Direct Storage
                                </h4>
                                <div className="w-full bg-[#070c18] h-2.5 rounded-full overflow-hidden border border-[#162242]">
                                    <div className="bg-purple-500 h-full" style={{ width: '28.4%' }} />
                                </div>
                                <div className="flex justify-between text-xs font-mono text-slate-400">
                                    <span>28.4 GB belegt</span>
                                    <span>{server.storage} GB Gesamt</span>
                                </div>
                            </div>
                        </div>
                    )}

                    {/* TAB 3: NETWORK */}
                    {activeTab === 'network' && (
                        <div className="space-y-4 text-xs font-mono">
                            <div className="rounded-2xl border border-[#192648] bg-[#0d1428] p-5 space-y-3">
                                <h4 className="font-bold text-white text-sm font-sans flex items-center gap-2">
                                    <Wifi className="h-4 w-4 text-blue-400" /> Zugewiesene IP-Adressen & Ports
                                </h4>

                                <div className="space-y-2 pt-2">
                                    <div className="flex justify-between items-center p-3 rounded-xl bg-[#070c18] border border-[#162242]">
                                        <div>
                                            <span className="text-slate-500 block text-[10px]">Haupt IPv4</span>
                                            <span className="font-bold text-white">{server.ip}</span>
                                        </div>
                                        <button onClick={copyIp} className="px-3 py-1 rounded bg-[#152243] text-blue-300 border border-[#23386d] hover:bg-[#1d2d58]">
                                            Kopieren
                                        </button>
                                    </div>

                                    <div className="flex justify-between items-center p-3 rounded-xl bg-[#070c18] border border-[#162242]">
                                        <div>
                                            <span className="text-slate-500 block text-[10px]">Reverse DNS (PTR)</span>
                                            <span className="font-bold text-emerald-400">{server.id}.nexushost.de</span>
                                        </div>
                                        <button className="px-3 py-1 rounded bg-[#152243] text-slate-300 border border-[#23386d] hover:bg-[#1d2d58]">
                                            Bearbeiten
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    )}

                    {/* TAB 4: BACKUPS */}
                    {activeTab === 'backups' && (
                        <div className="space-y-4">
                            <div className="flex items-center justify-between">
                                <h4 className="font-bold text-white text-sm">Automatisierte Server-Backups</h4>
                                <button className="px-4 py-2 rounded-xl bg-[#3b82f6] text-white font-bold text-xs hover:bg-[#2563eb]">
                                    + Neues Backup Jetzt Erstellen
                                </button>
                            </div>

                            <div className="space-y-2 text-xs font-mono">
                                <div className="p-4 rounded-xl border border-[#192648] bg-[#0d1428] flex items-center justify-between">
                                    <div>
                                        <div className="font-bold text-white">Auto-Backup 30.07.2026 03:00</div>
                                        <div className="text-slate-400 text-[11px]">Größe: 4.2 GB • Typ: Täglich</div>
                                    </div>
                                    <button className="px-3 py-1.5 rounded-lg bg-[#152243] text-blue-300 border border-[#23386d] hover:bg-[#1d2d58]">
                                        Wiederherstellen
                                    </button>
                                </div>
                                <div className="p-4 rounded-xl border border-[#192648] bg-[#0d1428] flex items-center justify-between">
                                    <div>
                                        <div className="font-bold text-white">Auto-Backup 29.07.2026 03:00</div>
                                        <div className="text-slate-400 text-[11px]">Größe: 4.1 GB • Typ: Täglich</div>
                                    </div>
                                    <button className="px-3 py-1.5 rounded-lg bg-[#152243] text-blue-300 border border-[#23386d] hover:bg-[#1d2d58]">
                                        Wiederherstellen
                                    </button>
                                </div>
                            </div>
                        </div>
                    )}
                </div>
            </div>
        </div>
    );
};
