"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import {
    LayoutDashboard,
    Download, CheckCircle, Upload, ArrowUpRight,
    Cpu, Database, ShieldCheck, FolderOpen,
    Settings, HeartPulse, Cloud, Bot, Captions, Disc,
    BookTemplate, HardDriveDownload, Shield, Zap, LogOut,
    ChevronRight, Activity, ListChecks, RefreshCcw
} from 'lucide-react';

import { clsx } from "clsx";
import { useRouter } from "next/navigation";
import { subscribeToEvents, formatBytes } from "@/lib/api";
import Logo from "@/components/Logo";

const menuItems = [
    { name: "Dashboard", href: "/", icon: LayoutDashboard },
    { name: "File Downloader", href: "/analyzer", icon: Download, description: "Download, Analyze & Process" },
    { name: "Active Jobs", href: "/jobs", icon: Cpu, description: "Live queue & logs" },
    { name: "File Pipeline", href: "/files", icon: FolderOpen, description: "Downloaded → Uploaded" },
];

const settingsItems = [
    { name: "Metadata Templates", href: "/settings/metadata", icon: ShieldCheck },
    { name: "Subtitle Branding", href: "/settings/subtitles", icon: Captions },
    { name: "Encoding Presets", href: "/settings/encoding", icon: Disc },
    { name: "Job Templates", href: "/settings/templates", icon: FolderOpen },
    { name: "Google Drive", href: "/settings/gdrive", icon: Cloud },
    { name: "Telegram / Discord", href: "/settings/notifications", icon: Bot },
    { name: "Webhooks", href: "/settings/webhooks", icon: Zap },
    { name: "Security / 2FA", href: "/settings/security", icon: Shield },
    { name: "Backup & Restore", href: "/settings/backup", icon: HardDriveDownload },
    { name: "General Settings", href: "/settings/general", icon: Settings },
    { name: "System Health", href: "/settings/health", icon: HeartPulse },
];

export default function Sidebar() {
    const pathname = usePathname();
    const router = useRouter();
    const [metrics, setMetrics] = useState<any>(null);

    const [unreadErrors, setUnreadErrors] = useState(0);
    const [showErrorModal, setShowErrorModal] = useState(false);
    const [errorLogs, setErrorLogs] = useState<any[]>([]);

    const handleLogout = () => {
        localStorage.removeItem("mhb_token");
        document.cookie = "mhb_token=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT";
        router.push("/login");
    };

    useEffect(() => {
        // Fetch initial error logs
        fetch(`${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3001'}/api/notifications/logs`, {
            headers: { 'x-auth-token': localStorage.getItem('mhb_token') || '' }
        })
            .then(res => res.json())
            .then(data => setErrorLogs(data))
            .catch(e => console.error("Failed to fetch logs", e));

        const unsubscribe = subscribeToEvents((event, data) => {
            if (event === 'system_metrics') {
                setMetrics(data);
            } else if (event === 'system_error') {
                setErrorLogs(prev => [data, ...prev].slice(0, 50));
                setUnreadErrors(prev => prev + 1);
            }
        });
        return () => unsubscribe();
    }, []);

    return (
        <>
        <aside className="w-72 bg-bg-secondary border-r border-white/5 flex flex-col h-full z-50 overflow-y-auto custom-scrollbar">
            {/* Brand */}
            <div className="p-8 pb-10 flex items-center justify-between">
                <Logo size="sm" />
                
                <button 
                    onClick={() => { setShowErrorModal(true); setUnreadErrors(0); }}
                    className="relative p-2 rounded-xl bg-white/5 hover:bg-white/10 transition-all group"
                >
                    <Activity className={clsx("w-4 h-4 transition-colors", unreadErrors > 0 ? "text-red-400 animate-pulse" : "text-white/20 group-hover:text-white/60")} />
                    {unreadErrors > 0 && (
                        <span className="absolute -top-1 -right-1 w-4 h-4 bg-red-500 text-[9px] font-black text-white flex items-center justify-center rounded-full border-2 border-bg-secondary animate-bounce">
                            {unreadErrors}
                        </span>
                    )}
                </button>
            </div>

            {/* Error Modal Overlay */}
            {showErrorModal && (
                <div className="fixed inset-0 z-[100] flex items-center justify-center p-4 bg-black/80 backdrop-blur-sm animate-fade-in">
                    <div className="bg-bg-secondary border border-white/10 w-full max-w-2xl rounded-3xl overflow-hidden shadow-2xl animate-scale-up">
                        <div className="p-6 border-b border-white/5 flex items-center justify-between bg-white/[0.02]">
                            <div className="flex items-center gap-3">
                                <Activity className="w-5 h-5 text-red-400" />
                                <h3 className="text-lg font-black text-white uppercase tracking-widest">System Error Logs</h3>
                            </div>
                            <button onClick={() => setShowErrorModal(false)} className="p-2 hover:bg-white/5 rounded-full transition-colors text-white/40">
                                <Zap className="w-5 h-5 rotate-45" />
                            </button>
                        </div>
                        <div className="max-h-[60vh] overflow-y-auto p-4 space-y-3 custom-scrollbar bg-black/20">
                            {errorLogs.length === 0 ? (
                                <div className="py-20 text-center space-y-4">
                                    <div className="w-16 h-16 bg-emerald-500/10 rounded-full flex items-center justify-center mx-auto">
                                        <ShieldCheck className="w-8 h-8 text-emerald-400" />
                                    </div>
                                    <p className="text-white/20 font-bold uppercase tracking-widest text-xs">System is healthy. No errors reported.</p>
                                </div>
                            ) : errorLogs.map(err => (
                                <div key={err.id} className="p-4 rounded-2xl bg-white/[0.03] border border-white/5 hover:bg-white/[0.05] transition-all group">
                                    <div className="flex items-start justify-between mb-2">
                                        <div>
                                            <p className="text-xs font-black text-red-400 uppercase tracking-widest mb-1">{err.title}</p>
                                            <p className="text-sm font-bold text-white/90 leading-tight">{err.message}</p>
                                        </div>
                                        <span className="text-[10px] font-mono text-white/20">{new Date(err.timestamp).toLocaleTimeString()}</span>
                                    </div>
                                    {err.details && (
                                        <details className="mt-2">
                                            <summary className="text-[10px] font-black uppercase text-white/20 cursor-pointer hover:text-white/40 transition-colors">View Exact Reason & Details</summary>
                                            <pre className="mt-2 p-3 rounded-xl bg-black/40 text-[10px] font-mono text-red-300/60 overflow-x-auto whitespace-pre-wrap border border-red-500/10">
                                                {err.details}
                                            </pre>
                                        </details>
                                    )}
                                </div>
                            ))}
                        </div>
                        <div className="p-6 bg-white/[0.02] border-t border-white/5 flex justify-end">
                            <button onClick={() => setShowErrorModal(false)} className="btn-primary px-8 py-3 rounded-2xl font-black text-xs uppercase tracking-widest">Close Logs</button>
                        </div>
                    </div>
                </div>
            )}

            {/* Main Nav */}
            <nav className="flex-1 px-4 space-y-1">
                <div className="mb-4">
                    <p className="section-title px-4 mb-3">Main Navigation</p>
                    {menuItems.map((item) => {
                        const active = pathname === item.href;
                        return (
                            <Link
                                key={item.href}
                                href={item.href}
                                className={clsx(
                                    "group relative flex items-center gap-3 py-3 px-4 rounded-xl transition-all duration-200 overflow-hidden",
                                    active
                                        ? "bg-accent-cyan text-white shadow-card"
                                        : "text-white/50 hover:bg-white/5 hover:text-white"
                                )}
                            >
                                <item.icon className={clsx("w-5 h-5 transition-transform duration-200", active ? "scale-110" : "group-hover:scale-110")} />
                                <div className="flex-1">
                                    <span className="font-semibold text-sm">{item.name}</span>
                                    {active && item.description && (
                                        <p className="text-[10px] text-white/70 font-medium">{item.description}</p>
                                    )}
                                </div>
                                {!active && <ChevronRight className="w-4 h-4 opacity-0 -translate-x-2 group-hover:opacity-40 group-hover:translate-x-0 transition-all" />}
                            </Link>
                        );
                    })}
                </div>

                <div>
                    <p className="section-title px-4 mb-3">Configuration</p>
                    {settingsItems.map((item) => {
                        const active = pathname === item.href;
                        return (
                            <Link
                                key={item.href}
                                href={item.href}
                                className={clsx(
                                    "group flex items-center gap-3 py-2.5 px-4 rounded-xl transition-all duration-200",
                                    active
                                        ? "bg-bg-card text-white shadow-card border border-white/10"
                                        : "text-white/60 hover:bg-white/5 hover:text-white"
                                )}
                            >
                                <item.icon className="w-4 h-4" />
                                <span className="font-medium text-sm">{item.name}</span>
                            </Link>
                        );
                    })}
                </div>

                {/* Logout Button (Moved up for visibility) */}
                <div className="px-4 mt-6 mb-2">
                    <button
                        onClick={handleLogout}
                        className="w-full flex items-center gap-3 py-3 px-4 rounded-xl text-red-400/60 hover:text-red-400 hover:bg-red-400/5 transition-all duration-200 group border border-transparent hover:border-red-400/10"
                    >
                        <LogOut className="w-5 h-5 group-hover:-translate-x-1 transition-transform" />
                        <span className="font-semibold text-sm">Logout Session</span>
                    </button>
                </div>
            </nav>

            {/* Footer / Status */}
            <div className="p-6 mt-auto">
                <div className="border border-white/10 bg-white/[0.04] rounded-2xl p-4">
                    <div className="flex items-center gap-3 mb-2">
                        <div className={clsx("w-1.5 h-1.5 rounded-full transition-all duration-500", metrics ? "bg-emerald-500  animate-pulse" : "bg-white/20")} />
                        <span className="text-xs font-semibold text-white/80">System Health</span>
                    </div>
                    {metrics ? (
                        <div className="space-y-2">
                            <div className="flex justify-between items-center text-[10px]">
                                <span className="text-white/50 uppercase font-bold tracking-tighter">CPU Load</span>
                                <span className="text-white font-mono">{metrics.cpu.usage}%</span>
                            </div>
                            <div className="w-full h-1 bg-white/10 rounded-full overflow-hidden">
                                <div
                                    className="h-full bg-accent-cyan  transition-all duration-1000"
                                    style={{ width: `${metrics.cpu.usage}%` }}
                                />
                            </div>
                            <div className="flex justify-between items-center text-[10px]">
                                <span className="text-white/50 uppercase font-bold tracking-tighter">RAM usage</span>
                                <span className="text-accent-violet font-mono">{formatBytes(metrics.ram.used).split(' ')[0]} / {formatBytes(metrics.ram.total)}</span>
                            </div>
                            <div className="w-full h-1 bg-white/5 rounded-full overflow-hidden">
                                <div
                                    className="h-full bg-accent-violet  transition-all duration-1000"
                                    style={{ width: `${metrics.ram.percent}%` }}
                                />
                            </div>

                            {/* 🚀 New: Real-time Worker Status Badge */}
                            <div className="pt-2 border-t border-white/5 mt-2">
                                <div className="flex items-center justify-between">
                                    <span className="text-[10px] text-white/50 uppercase font-bold tracking-tighter">Queue Worker</span>
                                    <div className={clsx(
                                        "flex items-center gap-1.5 px-2 py-0.5 rounded-full text-[9px] font-black uppercase tracking-widest transition-all duration-500",
                                        metrics.workerOnline 
                                            ? "bg-emerald-500/10 text-emerald-400 border border-emerald-500/20" 
                                            : "bg-red-500/10 text-red-400 border border-red-500/20 animate-pulse"
                                    )}>
                                        <div className={clsx("w-1 h-1 rounded-full", metrics.workerOnline ? "bg-emerald-400 animate-ping" : "bg-red-400")} />
                                        {metrics.workerOnline ? 'Online' : 'Offline'}
                                    </div>
                                </div>
                                {!metrics.workerOnline && metrics.workerError && (
                                    <p className="text-[8px] text-red-400/60 mt-1 font-bold uppercase tracking-tighter text-right animate-fade-in">
                                        Reason: {metrics.workerError}
                                    </p>
                                )}
                            </div>
                        </div>
                    ) : (
                        <p className="text-[10px] text-white/20 italic animate-pulse">Syncing nodes...</p>
                    )}
                </div>
            </div>
        </aside>
        </>
    );
}
