"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import {
    BarChart3,
    Clock,
    CheckCircle2,
    AlertCircle,
    Play,
    ArrowRight,
    Plus,
    Zap,
    Server,
    Cloud,
    ShieldCheck,
    Cpu,
    Database,
    Activity
} from "lucide-react";
import { clsx } from "clsx";
import { getJobs, formatBytes, statusBadgeClass, subscribeToEvents } from "@/lib/api";

export default function Dashboard() {
    const [stats, setStats] = useState({
        active: 0,
        completed: 0,
        failed: 0,
        total: 0
    });
    const [systemMetrics, setSystemMetrics] = useState<any>(null);
    const [recentJobs, setRecentJobs] = useState<any[]>([]);
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        async function loadData() {
            try {
                const { jobs } = await getJobs();
                setRecentJobs(jobs.slice(0, 5));
                setStats({
                    active: jobs.filter((j: any) => ['downloading', 'processing', 'uploading'].includes(j.status)).length,
                    completed: jobs.filter((j: any) => j.status === 'completed').length,
                    failed: jobs.filter((j: any) => j.status === 'failed').length,
                    total: jobs.length
                });
            } catch (err) {
                console.error(err);
            } finally {
                setLoading(false);
            }
        }
        loadData();

        // Subscribe to real-time events
        const unsubscribe = subscribeToEvents((event, data) => {
            if (event === 'system_metrics') {
                setSystemMetrics(data);
            }
            if (event === 'job_update') {
                loadData(); // Refresh list on job updates
            }
        });

        return () => unsubscribe();
    }, []);

    return (
        <div className="space-y-8 animate-fade-in shadow-2xl">
            {/* Header */}
            <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
                <div>
                    <h1 className="text-2xl md:text-3xl font-extrabold tracking-tight">System <span className="text-white">Overview</span></h1>
                    <p className="text-white/40 text-xs md:text-sm mt-1">Welcome back. Monitoring encoding nodes and stream health.</p>
                </div>
                <Link href="/analyzer" className="btn-primary">
                    <Plus className="w-4 h-4" />
                    New Encoding Job
                </Link>
            </div>

            {/* Stats Grid */}
            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
                <StatCard
                    label="Active Node Jobs"
                    value={stats.active}
                    icon={Zap}
                    color="cyan"
                    description="Processing in background"
                />
                <StatCard
                    label="Completed Today"
                    value={stats.completed}
                    icon={CheckCircle2}
                    color="emerald"
                    description="Ready for platform sync"
                />
                <StatCard
                    label="System Failures"
                    value={stats.failed}
                    icon={AlertCircle}
                    color="red"
                    description="Requires administrator review"
                />
                <StatCard
                    label="Total Processed"
                    value={stats.total}
                    icon={BarChart3}
                    color="violet"
                    description="Lifetime encoding count"
                />
            </div>

            <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
                {/* Recent Jobs */}
                <div className="lg:col-span-2 space-y-4">
                    <div className="flex items-center justify-between px-2">
                        <h2 className="text-sm font-bold uppercase tracking-widest text-white/40">Recent Activity</h2>
                        <Link href="/jobs" className="text-xs font-semibold text-white hover:underline flex items-center gap-1">
                            View All <ArrowRight className="w-3 h-3" />
                        </Link>
                    </div>

                    <div className="card divide-y divide-white/5">
                        {loading ? (
                            Array.from({ length: 5 }).map((_, i) => (
                                <div key={i} className="p-4 flex items-center gap-4 animate-pulse">
                                    <div className="w-10 h-10 rounded-lg skeleton shrink-0" />
                                    <div className="flex-1 space-y-2">
                                        <div className="h-4 w-1/2 skeleton" />
                                        <div className="h-3 w-1/4 skeleton" />
                                    </div>
                                    <div className="w-16 h-6 rounded-full skeleton" />
                                </div>
                            ))
                        ) : recentJobs.length === 0 ? (
                            <div className="p-12 text-center">
                                <div className="w-16 h-16 bg-white/5 rounded-full flex items-center justify-center mx-auto mb-4">
                                    <Clock className="w-8 h-8 text-white/10" />
                                </div>
                                <p className="text-white/30 text-sm font-medium">No recent jobs found</p>
                                <Link href="/analyzer" className="text-white text-xs mt-2 inline-block">Start your first job</Link>
                            </div>
                        ) : (
                            recentJobs.map((job) => (
                                <div key={job.id} className="p-4 flex items-center gap-4 hover:bg-white/[0.02] transition-colors">
                                    <div className={clsx(
                                        "w-10 h-10 rounded-lg flex items-center justify-center shrink-0",
                                        job.status === 'completed' ? "bg-emerald-500/10 text-emerald-400" : job.status === 'failed' ? "bg-red-500/10 text-red-400" : "bg-cyan-500/10 text-cyan-400"
                                    )}>
                                        {job.type === 'clean' ? <ShieldCheck className="w-5 h-5 text-current" /> : <Play className="w-5 h-5 text-current" />}
                                    </div>
                                    <div className="flex-1 min-w-0">
                                        <h3 className="font-semibold text-sm truncate">{job.original_file_name}</h3>
                                        <p className="text-[10px] text-white/30 uppercase font-bold tracking-tighter mt-0.5">
                                            {job.type} • {job.resolution} • {new Date(job.created_at).toLocaleDateString()}
                                        </p>
                                    </div>
                                    <div className="flex flex-col items-end gap-1">
                                        <span className={clsx("badge", statusBadgeClass(job.status))}>
                                            {job.status}
                                        </span>
                                        <span className="text-[10px] font-mono text-white/20">{formatBytes(job.file_info?.fileSize || 0)}</span>
                                    </div>
                                </div>
                            ))
                        )}
                    </div>
                </div>

                {/* System Metrics Sidebar */}
                <div className="space-y-6">
                    <div className="px-2">
                        <h2 className="text-sm font-bold uppercase tracking-widest text-white/40">Real-time Telemetry</h2>
                    </div>

                    <div className="space-y-4">
                        {systemMetrics ? (
                            <div className="card p-6 space-y-6 border-accent-cyan/10 bg-accent-cyan/[0.01]">
                                <MetricProgress
                                    label="CPU Load"
                                    value={systemMetrics.cpu.usage}
                                    icon={Cpu}
                                    color="cyan"
                                    subtext={`${systemMetrics.cpu.cores} Cores @ ${systemMetrics.cpu.model.split(' ')[0]}`}
                                />
                                <MetricProgress
                                    label="RAM Usage"
                                    value={systemMetrics.ram.percent}
                                    icon={Activity}
                                    color="violet"
                                    subtext={`${formatBytes(systemMetrics.ram.used)} / ${formatBytes(systemMetrics.ram.total)}`}
                                />
                                <MetricProgress
                                    label="Main Storage"
                                    value={systemMetrics.storage.percent}
                                    icon={Database}
                                    color="emerald"
                                    subtext={`${formatBytes(systemMetrics.storage.used)} / ${formatBytes(systemMetrics.storage.total)}`}
                                />

                                <div className="pt-2 border-t border-white/5 flex items-center justify-between">
                                    <span className="text-[10px] font-bold text-white/20 uppercase tracking-widest">OS: {systemMetrics.platform}</span>
                                    <div className="flex items-center gap-1.5">
                                        <div className="w-1.5 h-1.5 rounded-full bg-emerald-500 animate-pulse " />
                                        <span className="text-[10px] font-bold text-emerald-400 uppercase">System Online</span>
                                    </div>
                                </div>
                            </div>
                        ) : (
                            <div className="card p-12 text-center space-y-4 border-dashed border-white/10 opacity-20">
                                <Activity className="w-10 h-10 mx-auto animate-pulse" />
                                <p className="text-xs font-bold uppercase tracking-widest">Polling Metrics...</p>
                            </div>
                        )}

                        <div className="pt-4 px-2">
                            <h2 className="text-sm font-bold uppercase tracking-widest text-white/40 mb-4">Quick Links</h2>
                            <div className="space-y-3">
                                <QuickActionCard
                                    title="Cloud Encoder"
                                    subtitle="Optimized H.264/H.265"
                                    icon={Server}
                                    href="/analyzer"
                                    color="cyan"
                                />
                                <QuickActionCard
                                    title="Drive Storage"
                                    subtitle="GDrive API Sync"
                                    icon={Cloud}
                                    href="/settings/gdrive"
                                    color="violet"
                                />
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    );
}

function MetricProgress({ label, value, icon: Icon, color, subtext }: any) {
    const colors: any = {
        cyan: "bg-accent-cyan ",
        violet: "bg-accent-violet ",
        emerald: "bg-emerald-400 ",
    };

    const iconColors: any = {
        cyan: "text-white",
        violet: "text-accent-violet",
        emerald: "text-emerald-400",
    };

    return (
        <div className="space-y-3">
            <div className="flex justify-between items-end">
                <div className="flex items-center gap-2">
                    <Icon className={clsx("w-4 h-4", iconColors[color])} />
                    <span className="text-xs font-bold text-white/80">{label}</span>
                </div>
                <span className="font-mono text-xs font-black text-white/40">{value}%</span>
            </div>
            <div className="h-2 bg-white/5 rounded-full overflow-hidden">
                <div
                    className={clsx("h-full transition-all duration-1000 ease-out rounded-full", colors[color])}
                    style={{ width: `${value}%` }}
                />
            </div>
            <p className="text-[10px] text-white/20 font-medium tracking-tight uppercase">{subtext}</p>
        </div>
    );
}

function StatCard({ label, value, icon: Icon, color, description }: any) {
    const colors: any = {
        cyan: "text-white bg-accent-cyan/10 ring-accent-cyan/20",
        emerald: "text-emerald-400 bg-emerald-400/10 ring-emerald-400/20",
        red: "text-red-400 bg-red-400/10 ring-red-400/20",
        violet: "text-accent-violet bg-accent-violet/10 ring-accent-violet/20",
    };

    return (
        <div className="card p-5 hover:border-white/10 transition-colors group">
            <div className="flex items-start justify-between mb-4">
                <div className={clsx("p-2 rounded-lg ring-1 transition-transform group-hover:scale-110", colors[color])}>
                    <Icon className="w-5 h-5" />
                </div>
            </div>
            <div>
                <p className="text-white/30 text-[10px] font-extrabold uppercase tracking-widest mb-1">{label}</p>
                <h3 className="text-3xl font-black tracking-tight group-hover:text-white transition-colors">{value}</h3>
                <p className="text-white/20 text-[10px] font-medium mt-1 uppercase leading-none">{description}</p>
            </div>
        </div>
    );
}

function QuickActionCard({ title, subtitle, icon: Icon, href, color }: any) {
    const colors: any = {
        cyan: "text-white border-accent-cyan/5 hover:bg-accent-cyan/[0.03]",
        violet: "text-accent-violet border-accent-violet/5 hover:bg-accent-violet/[0.03]"
    };

    return (
        <Link href={href} className={clsx("flex items-center gap-4 p-4 card hover:translate-x-1 transition-all group", colors[color])}>
            <div className="w-10 h-10 rounded-lg bg-white/5 flex items-center justify-center shrink-0 group-hover:scale-110 transition-transform">
                <Icon className="w-5 h-5" />
            </div>
            <div className="flex-1">
                <h4 className="text-sm font-bold text-white group-hover:text-current transition-colors">{title}</h4>
                <p className="text-[10px] font-bold uppercase tracking-tight text-white/30">{subtitle}</p>
            </div>
            <ArrowRight className="w-4 h-4 text-white/20 group-hover:text-current group-hover:translate-x-1 transition-all" />
        </Link>
    );
}
