import { DeployModal } from '@/components/dashboard/DeployModal';
import { ServerConsoleModal } from '@/components/dashboard/ServerConsoleModal';
import { ServerInstance } from '@/components/dashboard/ServerList';
import { Head, Link, usePage } from '@inertiajs/react';
import { Bell, Calendar, Clock, CreditCard, Gamepad2, HardDrive, Headphones, Megaphone, Plus, Search, Server, Shield, Sparkles, Terminal, Wallet, Zap } from 'lucide-react';
import React, { useEffect, useState } from 'react';
import { AppSidebar } from '@/components/app-sidebar';

export default function Dashboard() {
    const { auth } = usePage<any>().props;
    const userName = auth?.user?.name || 'Luca';

    const [isDeployOpen, setIsDeployOpen] = useState(false);
    const [consoleServer, setConsoleServer] = useState<ServerInstance | null>(null);
    const [searchQuery, setSearchQuery] = useState('');
    const [credit, setCredit] = useState(20015.00);

    const [userServers, setUserServers] = useState<any[]>([]);

    useEffect(() => {
        const handleTopUp = () => {
            setCredit((prev) => prev + 50.0);
        };
        window.addEventListener('open-topup-modal', handleTopUp);

        // Fetch real servers from API
        fetch('/api/minecraft/list')
            .then((res) => res.json())
            .then((data) => {
                if (data && data.success && Array.isArray(data.servers)) {
                    const currentUser = auth?.user;
                    const isOwner = currentUser && (currentUser.id === 1 || currentUser.role === 'Superadmin' || currentUser.role === 'admin');

                    if (isOwner) {
                        setUserServers(data.servers);
                    } else {
                        const userNumId = `#${1000 + (currentUser?.id || 1)}`;
                        const rawId = String(currentUser?.id || '');
                        const filtered = data.servers.filter((s: any) => {
                            return (
                                s.customerId === userNumId ||
                                s.customer_id === userNumId ||
                                s.customerId === rawId ||
                                s.customer_id === rawId ||
                                s.user_id === rawId ||
                                s.customerName?.toLowerCase() === currentUser?.name?.toLowerCase()
                            );
                        });
                        setUserServers(filtered.length > 0 ? filtered : []);
                    }
                }
            })
            .catch(() => {});

        return () => window.removeEventListener('open-topup-modal', handleTopUp);
    }, []);

    const [maintenance, setMaintenance] = useState<{ active: boolean; message: string }>({ active: false, message: '' });

    React.useEffect(() => {
        fetch('/api/admin/maintenance')
            .then((res) => res.json())
            .then((data) => {
                if (data.success && data.active) {
                    setMaintenance({ active: true, message: data.message });
                }
            })
            .catch(() => {});
    }, []);

    return (
        <>
            <Head title="Dashboard - Rose Hosting" />

            {/* Global Maintenance Banner */}
            {maintenance.active && (
                <div className="bg-gradient-to-r from-red-950 via-rose-900 to-red-950 border-b border-red-700/80 px-6 py-2.5 text-center text-xs font-mono font-bold text-white shadow-xl flex items-center justify-center gap-3 animate-pulse z-50">
                    <Megaphone className="h-4 w-4 text-amber-300 flex-shrink-0" />
                    <span>{maintenance.message}</span>
                </div>
            )}

            <div className="flex min-h-screen bg-[#070405] text-slate-100 font-sans selection:bg-rose-600 selection:text-white">
                {/* Left Sidebar */}
                <AppSidebar />

                {/* Main Content Area */}
                <main className="flex-1 flex flex-col min-w-0 bg-[#070405]">
                    {/* Top Header Bar */}
                    <header className="sticky top-0 z-40 bg-[#070405]/90 backdrop-blur-md border-b border-[#260f14] px-6 py-3.5 flex items-center justify-between gap-4">
                        {/* Search Input */}
                        <div className="relative w-full max-w-md">
                            <Search className="absolute left-3.5 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-500" />
                            <input
                                type="text"
                                value={searchQuery}
                                onChange={(e) => setSearchQuery(e.target.value)}
                                placeholder="Suche nach Servern..."
                                className="w-full bg-[#14070a] border border-[#36131b] rounded-xl pl-10 pr-12 py-2 text-xs font-medium text-slate-200 placeholder:text-slate-500 outline-none focus:border-red-500 transition-colors"
                            />
                            <kbd className="absolute right-3 top-1/2 -translate-y-1/2 px-1.5 py-0.5 text-[10px] font-mono text-slate-400 bg-[#24080e] border border-[#3d121b] rounded">
                                ⌘ K
                            </kbd>
                        </div>

                        {/* Right Top Bar Controls */}
                        <div className="flex items-center gap-4">
                            {/* Bell notification */}
                            <button className="relative p-2 rounded-xl bg-[#14070a] border border-[#36131b] text-slate-300 hover:text-white hover:border-rose-500/50 transition-all">
                                <Bell className="h-4 w-4" />
                                <span className="absolute -top-1 -right-1 flex h-4 w-4 items-center justify-center rounded-full bg-red-600 text-[9px] font-bold text-white">
                                    3
                                </span>
                            </button>

                            {/* User Profile Pill */}
                            <div className="flex items-center gap-2.5 bg-[#14070a] border border-[#36131b] rounded-xl px-3 py-1.5">
                                <div className="h-7 w-7 rounded-lg bg-red-600 flex items-center justify-center font-bold text-xs text-white">
                                    {userName.charAt(0).toUpperCase()}
                                </div>
                                <div className="flex flex-col text-left">
                                    <span className="text-xs font-bold text-white leading-tight">{userName}</span>
                                    <span className="text-[10px] text-slate-400 font-mono">Kunden-ID: #4581</span>
                                </div>
                            </div>

                            {/* Primary Red Button */}
                            <button
                                onClick={() => setIsDeployOpen(true)}
                                className="flex items-center gap-1.5 bg-red-600 hover:bg-red-700 text-white px-4 py-2 rounded-xl text-xs font-bold shadow-lg shadow-red-600/25 active:scale-95 transition-all"
                            >
                                <Plus className="h-4 w-4 stroke-[3]" />
                                Neuen Server bestellen
                            </button>
                        </div>
                    </header>

                    {/* Dashboard Page Body Container */}
                    <div className="p-6 sm:p-8 space-y-6 max-w-7xl mx-auto w-full">


                        {/* Greeting Header */}
                        <div>
                            <h1 className="text-2xl sm:text-3xl font-extrabold text-white tracking-tight flex items-center gap-2">
                                Hallo {userName}! 👋
                            </h1>
                            <p className="text-xs sm:text-sm text-slate-400 mt-1">
                                Übersicht deiner Server und Services bei Rose Hosting
                            </p>
                        </div>

                        {/* 4 Stat Cards Grid */}
                        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
                            {/* Card 1: Aktive Server */}
                            <div className="rounded-2xl border border-[#260e13] bg-[#0c0507] p-5 flex items-center justify-between">
                                <div className="space-y-1">
                                    <span className="text-[10px] font-mono font-bold uppercase tracking-wider text-slate-400">
                                        AKTIVE SERVER
                                    </span>
                                    <div className="text-2xl font-black text-white font-mono">1 / 5</div>
                                    <div className="flex items-center gap-1.5 text-xs text-emerald-400">
                                        <span className="h-2 w-2 rounded-full bg-emerald-500 animate-ping inline-block" />
                                        <span>1 online</span>
                                    </div>
                                </div>
                                <div className="p-3 rounded-2xl bg-[#1c0a0e] border border-[#38131d] text-rose-400">
                                    <Server className="h-6 w-6" />
                                </div>
                            </div>

                            {/* Card 2: Laufzeit */}
                            <div className="rounded-2xl border border-[#260e13] bg-[#0c0507] p-5 flex items-center justify-between">
                                <div className="space-y-1">
                                    <span className="text-[10px] font-mono font-bold uppercase tracking-wider text-slate-400">
                                        LAUFZEIT
                                    </span>
                                    <div className="text-2xl font-black text-white font-mono">28 Tage</div>
                                    <div className="text-xs text-slate-400">Nächste Zahlung: 18.08.2026</div>
                                </div>
                                <div className="p-3 rounded-2xl bg-[#1c0a0e] border border-[#38131d] text-rose-500">
                                    <Clock className="h-6 w-6" />
                                </div>
                            </div>

                            {/* Card 3: Gesamtpreis */}
                            <div className="rounded-2xl border border-[#260e13] bg-[#0c0507] p-5 flex items-center justify-between">
                                <div className="space-y-1">
                                    <span className="text-[10px] font-mono font-bold uppercase tracking-wider text-slate-400">
                                        GESAMTPREIS
                                    </span>
                                    <div className="text-2xl font-black text-white font-mono">0,00 € <span className="text-xs font-normal text-slate-400">/ MON.</span></div>
                                    <div className="text-xs text-slate-400">Inkl. MwSt.</div>
                                </div>
                                <div className="p-3 rounded-2xl bg-[#1c0a0e] border border-[#38131d] text-red-400">
                                    <CreditCard className="h-6 w-6" />
                                </div>
                            </div>

                            {/* Card 4: Offene Rechnungen */}
                            <div className="rounded-2xl border border-[#260e13] bg-[#0c0507] p-5 flex items-center justify-between">
                                <div className="space-y-1">
                                    <span className="text-[10px] font-mono font-bold uppercase tracking-wider text-slate-400">
                                        OFFENE RECHNUNGEN
                                    </span>
                                    <div className="text-2xl font-black text-white font-mono">0</div>
                                    <div className="text-xs text-slate-400">Alles bezahlt! 🎉</div>
                                </div>
                                <div className="p-3 rounded-2xl bg-[#1c0a0e] border border-[#38131d] text-rose-400">
                                    <Wallet className="h-6 w-6" />
                                </div>
                            </div>
                        </div>

                        {/* Main Grid Section (2 Columns) */}
                        <div className="grid grid-cols-1 lg:grid-cols-12 gap-6">
                            {/* Left Column: Server List (8 Cols) */}
                            <div className="lg:col-span-8 space-y-6">
                                <div>
                                    <h2 className="text-lg font-extrabold text-white mb-3">Deine Server</h2>

                                    {userServers.length === 0 ? (
                                        <div className="rounded-2xl border border-[#260e13] bg-[#0c0507] p-8 text-center space-y-3 shadow-xl">
                                            <div className="h-12 w-12 rounded-2xl bg-red-600/20 border border-red-500/30 text-rose-400 flex items-center justify-center mx-auto">
                                                <Server className="h-6 w-6" />
                                            </div>
                                            <h3 className="font-bold text-white text-base">Du hast noch keine aktiven Server</h3>
                                            <p className="text-xs text-slate-400 max-w-sm mx-auto">
                                                Erstelle deinen ersten Server im Dashboard oder fordere eine Zuweisung über das Admin Panel an.
                                            </p>
                                            <button
                                                onClick={() => setIsDeployOpen(true)}
                                                className="mt-2 px-5 py-2.5 rounded-xl bg-red-600 hover:bg-red-700 text-white text-xs font-bold shadow-lg shadow-red-600/25 active:scale-95 transition-all inline-flex items-center gap-1.5"
                                            >
                                                <Plus className="h-4 w-4" /> Ersten Server bestellen
                                            </button>
                                        </div>
                                    ) : (
                                        <div className="space-y-4">
                                            {userServers.map((srv) => (
                                                <div key={srv.id} className="rounded-2xl border border-[#260e13] bg-[#0c0507] p-5 hover:border-rose-500/50 transition-all shadow-xl space-y-4">
                                                    <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
                                                        <div className="flex items-center gap-3.5">
                                                            <div className="h-12 w-12 rounded-xl bg-gradient-to-br from-emerald-600 to-green-700 flex items-center justify-center text-white shadow-md flex-shrink-0">
                                                                <Gamepad2 className="h-6 w-6" />
                                                            </div>

                                                            <div>
                                                                <div className="flex items-center gap-3">
                                                                    <h3 className="font-bold text-white text-base">{srv.name}</h3>
                                                                    <span className={`px-2 py-0.5 rounded-full text-[10px] font-mono font-semibold flex items-center gap-1 border ${srv.status === 'online' ? 'bg-emerald-950 text-emerald-400 border-emerald-800' : 'bg-red-950 text-red-400 border-red-800'}`}>
                                                                        <span className={`h-1.5 w-1.5 rounded-full ${srv.status === 'online' ? 'bg-emerald-400 animate-ping' : 'bg-red-400'}`} />
                                                                        {srv.status.toUpperCase()}
                                                                    </span>
                                                                </div>
                                                                <p className="text-xs font-mono text-slate-400 mt-0.5">
                                                                    {srv.ip} • {srv.type}
                                                                </p>
                                                            </div>
                                                        </div>

                                                        <Link
                                                            href={`/server/manage?id=${srv.id}`}
                                                            className="px-5 py-2 rounded-xl bg-red-600 hover:bg-red-700 text-white font-bold text-xs shadow-md shadow-red-600/25 active:scale-95 transition-all self-start sm:self-auto inline-flex items-center justify-center"
                                                        >
                                                            Verwalten
                                                        </Link>
                                                    </div>

                                                    <div className="pt-3 border-t border-[#1f0b0f] grid grid-cols-3 gap-2 text-center text-xs font-mono">
                                                        <div className="bg-[#050203] py-2 rounded-xl border border-[#210a0f]">
                                                            <span className="text-slate-500 text-[10px] block">IP & PORT</span>
                                                            <span className="font-bold text-rose-400 text-[11px]">{srv.ip}</span>
                                                        </div>
                                                        <div className="bg-[#050203] py-2 rounded-xl border border-[#210a0f]">
                                                            <span className="text-slate-500 text-[10px] block">CPU</span>
                                                            <span className="font-bold text-slate-200">{srv.cpu || 4} Cores</span>
                                                        </div>
                                                        <div className="bg-[#050203] py-2 rounded-xl border border-[#210a0f]">
                                                            <span className="text-slate-500 text-[10px] block">RAM</span>
                                                            <span className="font-bold text-slate-200">{srv.ram || 8} GB</span>
                                                        </div>
                                                    </div>
                                                </div>
                                            ))}
                                        </div>
                                    )}
                                </div>

                                {/* Schnellzugriff Section */}
                                <div className="pt-2">
                                    <h3 className="text-sm font-bold text-white mb-3">Schnellzugriff</h3>
                                    <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
                                        <a href="/#products" className="p-4 rounded-xl border border-[#260e13] bg-[#0c0507] hover:bg-[#14070a] hover:border-rose-500/40 transition-all text-center space-y-2">
                                            <Gamepad2 className="h-5 w-5 text-rose-400 mx-auto" />
                                            <span className="text-xs font-semibold text-slate-200 block">Gameserver</span>
                                        </a>
                                        <a href="/#vps-calculator" className="p-4 rounded-xl border border-[#260e13] bg-[#0c0507] hover:bg-[#14070a] hover:border-rose-500/40 transition-all text-center space-y-2">
                                            <Zap className="h-5 w-5 text-red-400 mx-auto" />
                                            <span className="text-xs font-semibold text-slate-200 block">Cloud VPS</span>
                                        </a>
                                        <a href="/dashboard#billing" className="p-4 rounded-xl border border-[#260e13] bg-[#0c0507] hover:bg-[#14070a] hover:border-rose-500/40 transition-all text-center space-y-2">
                                            <CreditCard className="h-5 w-5 text-rose-500 mx-auto" />
                                            <span className="text-xs font-semibold text-slate-200 block">Rechnungen</span>
                                        </a>
                                        <a href="/dashboard#support" className="p-4 rounded-xl border border-[#260e13] bg-[#0c0507] hover:bg-[#14070a] hover:border-rose-500/40 transition-all text-center space-y-2">
                                            <Headphones className="h-5 w-5 text-rose-300 mx-auto" />
                                            <span className="text-xs font-semibold text-slate-200 block">Support 24/7</span>
                                        </a>
                                    </div>
                                </div>
                            </div>

                            {/* Right Column: Payments & Support (4 Cols) */}
                            <div className="lg:col-span-4 space-y-6">
                                {/* Card 1: Deine nächste Zahlung */}
                                <div className="rounded-2xl border border-[#260e13] bg-[#0c0507] p-5 space-y-4 shadow-xl">
                                    <div className="flex items-center justify-between border-b border-[#1f0b0f] pb-3">
                                        <h3 className="text-sm font-bold text-white">Deine nächste Zahlung</h3>
                                        <CreditCard className="h-4 w-4 text-rose-400" />
                                    </div>

                                    <div className="space-y-1 font-mono">
                                        <div className="text-xs text-slate-300 font-bold">18.08.2026</div>
                                        <div className="text-[11px] text-slate-400">Zahlungsart: PayPal</div>
                                    </div>

                                    <div className="text-3xl font-black text-white font-mono">
                                        0,00 €
                                    </div>

                                    <a
                                        href="/dashboard#billing"
                                        className="w-full py-2.5 px-4 rounded-xl bg-[#1c0a0e] border border-[#38131d] text-xs font-bold text-slate-200 hover:bg-[#280e14] hover:text-white transition-all text-center block"
                                    >
                                        Rechnungen anzeigen
                                    </a>
                                </div>

                                {/* Card 2: Support */}
                                <div className="rounded-2xl border border-[#260e13] bg-[#0c0507] p-5 space-y-4 shadow-xl">
                                    <div className="flex items-center justify-between border-b border-[#1f0b0f] pb-3">
                                        <h3 className="text-sm font-bold text-white">Support</h3>
                                        <Headphones className="h-4 w-4 text-rose-400" />
                                    </div>

                                    <p className="text-xs text-slate-400 leading-relaxed">
                                        Wir sind für dich da! Erhalte schnelle Hilfe von unserem Support-Team rund um die Uhr.
                                    </p>

                                    <a
                                        href="/dashboard#support"
                                        className="w-full py-2.5 px-4 rounded-xl bg-[#1c0a0e] border border-[#38131d] text-xs font-bold text-rose-300 hover:bg-[#280e14] hover:text-white transition-all text-center block"
                                    >
                                        Support öffnen →
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>
                </main>
            </div>

            {/* Console Modal */}
            <ServerConsoleModal
                server={consoleServer}
                onClose={() => setConsoleServer(null)}
            />

            {/* Deploy Modal */}
            <DeployModal
                isOpen={isDeployOpen}
                onClose={() => setIsDeployOpen(false)}
            />
        </>
    );
}
