import { Activity, Copy, Cpu, Globe, HardDrive, Layers, MoreVertical, Play, RefreshCw, Server, Square, Terminal, Zap } from 'lucide-react';
import React, { useState } from 'react';

export interface ServerInstance {
    id: string;
    name: string;
    type: string;
    ip: string;
    location: string;
    flag: string;
    vcpu: number;
    ram: number;
    storage: number;
    status: 'online' | 'starting' | 'stopping' | 'offline';
    cpuUsage: number;
    ramUsage: number;
    monthlyPrice: string;
}

interface ServerListProps {
    onOpenConsole: (server: ServerInstance) => void;
    onOpenDeploy: () => void;
}

const INITIAL_SERVERS: ServerInstance[] = [
    {
        id: 'srv-fra-mc01',
        name: 'Minecraft Community Server (Paper 1.21)',
        type: 'Gameserver Pro',
        ip: '185.220.101.44:25565',
        location: 'Frankfurt (DE)',
        flag: '🇩🇪',
        vcpu: 4,
        ram: 12,
        storage: 160,
        status: 'online',
        cpuUsage: 22,
        ramUsage: 7.8,
        monthlyPrice: '12,50',
    },
    {
        id: 'srv-fra-vps02',
        name: 'Docker Web & API Node',
        type: 'Cloud VPS',
        ip: '185.220.101.99',
        location: 'Frankfurt (DE)',
        flag: '🇩🇪',
        vcpu: 2,
        ram: 4,
        storage: 60,
        status: 'online',
        cpuUsage: 14,
        ramUsage: 1.9,
        monthlyPrice: '5,90',
    },
    {
        id: 'srv-nyc-bot03',
        name: 'Discord Worker Bot Node',
        type: 'Starter VPS',
        ip: '198.51.100.12',
        location: 'New York (US)',
        flag: '🇺🇸',
        vcpu: 1,
        ram: 2,
        storage: 30,
        status: 'offline',
        cpuUsage: 0,
        ramUsage: 0,
        monthlyPrice: '3,50',
    },
];

export const ServerList: React.FC<ServerListProps> = ({ onOpenConsole, onOpenDeploy }) => {
    const [servers, setServers] = useState<ServerInstance[]>(INITIAL_SERVERS);
    const [selectedServerId, setSelectedServerId] = useState<string>('srv-fra-mc01');
    const [copiedIp, setCopiedIp] = useState<string | null>(null);

    const selectedServer = servers.find((s) => s.id === selectedServerId) || servers[0];

    const handlePower = (id: string, action: 'start' | 'stop' | 'restart') => {
        setServers((prev) =>
            prev.map((srv) => {
                if (srv.id !== id) return srv;
                if (action === 'stop') {
                    return { ...srv, status: 'offline', cpuUsage: 0, ramUsage: 0 };
                } else if (action === 'start') {
                    return { ...srv, status: 'online', cpuUsage: 18, ramUsage: srv.ram * 0.4 };
                } else {
                    return { ...srv, status: 'starting' };
                }
            })
        );

        if (action === 'restart') {
            setTimeout(() => {
                setServers((prev) =>
                    prev.map((srv) => (srv.id === id ? { ...srv, status: 'online', cpuUsage: 15 } : srv))
                );
            }, 1200);
        }
    };

    const copyToClipboard = (text: string) => {
        navigator.clipboard.writeText(text);
        setCopiedIp(text);
        setTimeout(() => setCopiedIp(null), 2000);
    };

    return (
        <div className="space-y-6">
            {/* Top Toolbar */}
            <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 bg-slate-900/60 p-4 rounded-2xl border border-slate-800">
                <div>
                    <h2 className="text-xl font-bold text-white flex items-center gap-2">
                        <Server className="h-5 w-5 text-cyan-400" /> Meine Server-Instanzen
                    </h2>
                    <p className="text-xs text-slate-400 mt-0.5">
                        Verwalte deine aktiven KVM-Root-Server, Spiele-Nodes und IP-Adressen in Echtzeit.
                    </p>
                </div>

                <button
                    onClick={onOpenDeploy}
                    className="inline-flex items-center gap-2 rounded-xl bg-gradient-to-r from-cyan-400 via-blue-500 to-indigo-500 px-4 py-2.5 text-xs font-bold text-slate-950 shadow-lg shadow-cyan-500/20 hover:brightness-110 transition-all"
                >
                    <Zap className="h-4 w-4 fill-slate-950" />
                    + Neuen Server Erstellen
                </button>
            </div>

            {/* Main Server Cards Grid */}
            <div className="grid grid-cols-1 lg:grid-cols-12 gap-6">
                {/* Left Server Selection List */}
                <div className="lg:col-span-7 space-y-3">
                    {servers.map((srv) => {
                        const isSelected = srv.id === selectedServerId;
                        return (
                            <div
                                key={srv.id}
                                onClick={() => setSelectedServerId(srv.id)}
                                className={`rounded-2xl border p-5 transition-all cursor-pointer relative ${
                                    isSelected
                                        ? 'border-cyan-500 bg-slate-900/90 shadow-lg shadow-cyan-950/40 ring-1 ring-cyan-500/50'
                                        : 'border-slate-800 bg-slate-900/40 hover:border-slate-700 hover:bg-slate-900/60'
                                }`}
                            >
                                <div className="flex items-start justify-between gap-4">
                                    <div className="flex items-center gap-3">
                                        <span className="text-2xl">{srv.flag}</span>
                                        <div>
                                            <div className="flex items-center gap-2">
                                                <h3 className="font-bold text-white text-sm">{srv.name}</h3>
                                                <span className="text-[10px] font-mono font-medium px-2 py-0.5 rounded bg-slate-800 text-slate-300 border border-slate-700">
                                                    {srv.type}
                                                </span>
                                            </div>
                                            <div className="flex items-center gap-3 text-xs text-slate-400 mt-1 font-mono">
                                                <span className="flex items-center gap-1 text-slate-300">
                                                    {srv.ip}
                                                    <button
                                                        onClick={(e) => {
                                                            e.stopPropagation();
                                                            copyToClipboard(srv.ip);
                                                        }}
                                                        className="text-slate-500 hover:text-cyan-400"
                                                        title="IP kopieren"
                                                    >
                                                        <Copy className="h-3 w-3" />
                                                    </button>
                                                </span>
                                                {copiedIp === srv.ip && (
                                                    <span className="text-[10px] text-emerald-400 font-sans">Kopiert!</span>
                                                )}
                                            </div>
                                        </div>
                                    </div>

                                    {/* Status Badge & Power Actions */}
                                    <div className="flex items-center gap-2">
                                        <span
                                            className={`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-[10px] font-mono font-semibold uppercase ${
                                                srv.status === 'online'
                                                    ? 'bg-emerald-950/80 text-emerald-400 border border-emerald-800/50'
                                                    : srv.status === 'offline'
                                                    ? 'bg-red-950/80 text-red-400 border border-red-800/50'
                                                    : 'bg-yellow-950/80 text-yellow-400 border border-yellow-800/50 animate-pulse'
                                            }`}
                                        >
                                            <span
                                                className={`h-1.5 w-1.5 rounded-full ${
                                                    srv.status === 'online'
                                                        ? 'bg-emerald-400 animate-ping'
                                                        : srv.status === 'offline'
                                                        ? 'bg-red-400'
                                                        : 'bg-yellow-400'
                                                }`}
                                            />
                                            {srv.status}
                                        </span>

                                        <div className="flex items-center gap-1" onClick={(e) => e.stopPropagation()}>
                                            {srv.status === 'offline' ? (
                                                <button
                                                    onClick={() => handlePower(srv.id, 'start')}
                                                    className="p-1.5 rounded-lg bg-emerald-950 text-emerald-400 border border-emerald-800 hover:bg-emerald-900"
                                                    title="Server Starten"
                                                >
                                                    <Play className="h-3.5 w-3.5 fill-emerald-400" />
                                                </button>
                                            ) : (
                                                <>
                                                    <button
                                                        onClick={() => handlePower(srv.id, 'restart')}
                                                        className="p-1.5 rounded-lg bg-yellow-950 text-yellow-400 border border-yellow-800 hover:bg-yellow-900"
                                                        title="Neu Starten"
                                                    >
                                                        <RefreshCw className="h-3.5 w-3.5" />
                                                    </button>
                                                    <button
                                                        onClick={() => handlePower(srv.id, 'stop')}
                                                        className="p-1.5 rounded-lg bg-red-950 text-red-400 border border-red-800 hover:bg-red-900"
                                                        title="Ausschalten"
                                                    >
                                                        <Square className="h-3.5 w-3.5 fill-red-400" />
                                                    </button>
                                                </>
                                            )}
                                        </div>
                                    </div>
                                </div>

                                {/* Hardware specs summary */}
                                <div className="mt-4 pt-3 border-t border-slate-800/60 flex items-center justify-between text-xs text-slate-400 font-mono">
                                    <div className="flex items-center gap-4">
                                        <span className="flex items-center gap-1">
                                            <Cpu className="h-3.5 w-3.5 text-cyan-400" /> {srv.vcpu} Cores
                                        </span>
                                        <span className="flex items-center gap-1">
                                            <Layers className="h-3.5 w-3.5 text-blue-400" /> {srv.ram} GB RAM
                                        </span>
                                        <span className="flex items-center gap-1">
                                            <HardDrive className="h-3.5 w-3.5 text-indigo-400" /> {srv.storage} GB NVMe
                                        </span>
                                    </div>
                                    <span className="text-slate-300 font-semibold">€{srv.monthlyPrice}/mtl.</span>
                                </div>
                            </div>
                        );
                    })}
                </div>

                {/* Right Server Detail Inspector */}
                <div className="lg:col-span-5 rounded-2xl border border-slate-800 bg-slate-900/80 p-6 space-y-6">
                    <div className="flex items-center justify-between border-b border-slate-800 pb-4">
                        <div>
                            <span className="text-[10px] font-mono uppercase tracking-widest text-cyan-400">
                                Ausgewählter Server
                            </span>
                            <h3 className="text-base font-bold text-white truncate max-w-[220px]">
                                {selectedServer.name}
                            </h3>
                        </div>
                        <button
                            onClick={() => onOpenConsole(selectedServer)}
                            className="inline-flex items-center gap-1.5 rounded-lg bg-cyan-950 border border-cyan-800 px-3 py-1.5 text-xs font-semibold text-cyan-400 hover:bg-cyan-900 transition-all"
                        >
                            <Terminal className="h-3.5 w-3.5" />
                            Web-Konsole
                        </button>
                    </div>

                    {/* Live Usage Gauges */}
                    <div className="space-y-4">
                        {/* CPU */}
                        <div>
                            <div className="flex justify-between text-xs font-mono mb-1">
                                <span className="text-slate-400">CPU-Auslastung</span>
                                <span className="text-cyan-400 font-bold">{selectedServer.cpuUsage}%</span>
                            </div>
                            <div className="w-full bg-slate-800 h-2 rounded-full overflow-hidden">
                                <div
                                    className="bg-cyan-400 h-full transition-all duration-500"
                                    style={{ width: `${selectedServer.cpuUsage}%` }}
                                />
                            </div>
                        </div>

                        {/* RAM */}
                        <div>
                            <div className="flex justify-between text-xs font-mono mb-1">
                                <span className="text-slate-400">RAM-Belegung</span>
                                <span className="text-blue-400 font-bold">
                                    {selectedServer.ramUsage} GB / {selectedServer.ram} GB
                                </span>
                            </div>
                            <div className="w-full bg-slate-800 h-2 rounded-full overflow-hidden">
                                <div
                                    className="bg-blue-400 h-full transition-all duration-500"
                                    style={{ width: `${(selectedServer.ramUsage / selectedServer.ram) * 100}%` }}
                                />
                            </div>
                        </div>
                    </div>

                    {/* Network & IP info */}
                    <div className="rounded-xl bg-slate-950 border border-slate-800 p-4 space-y-2.5 text-xs font-mono">
                        <div className="flex justify-between py-1 border-b border-slate-900">
                            <span className="text-slate-400">Primary IPv4</span>
                            <span className="text-white font-semibold">{selectedServer.ip.split(':')[0]}</span>
                        </div>
                        <div className="flex justify-between py-1 border-b border-slate-900">
                            <span className="text-slate-400">IPv6 Subnet</span>
                            <span className="text-purple-400 truncate max-w-[150px]">2a01:4f8:1c1a::/64</span>
                        </div>
                        <div className="flex justify-between py-1 border-b border-slate-900">
                            <span className="text-slate-400">PTR / Reverse DNS</span>
                            <span className="text-emerald-400 truncate max-w-[150px]">{selectedServer.id}.apexnode.net</span>
                        </div>
                        <div className="flex justify-between py-1">
                            <span className="text-slate-400">Auto-Backup Status</span>
                            <span className="text-emerald-400">Aktiv (Täglich 03:00)</span>
                        </div>
                    </div>

                    <div className="pt-2 grid grid-cols-2 gap-2 text-xs">
                        <button className="py-2 px-3 rounded-lg border border-slate-800 bg-slate-900 text-slate-300 hover:border-slate-700 hover:bg-slate-800 text-center font-medium">
                            Snapshot Erstellen
                        </button>
                        <button className="py-2 px-3 rounded-lg border border-slate-800 bg-slate-900 text-slate-300 hover:border-slate-700 hover:bg-slate-800 text-center font-medium">
                            Firewall-Regeln
                        </button>
                    </div>
                </div>
            </div>
        </div>
    );
};
