"use client";
import { useState, useEffect } from "react";
import { HeartPulse, CheckCircle2, XCircle, Loader2, RefreshCcw, HardDrive, Cpu, Database, Zap } from "lucide-react";

const API = process.env.NEXT_PUBLIC_API_URL || "http://localhost:3001";

export default function SystemHealthPage() {
    const [stats, setStats] = useState<any>(null);
    const [loading, setLoading] = useState(true);

    const authHeaders = () => {
        const token = typeof window !== "undefined" ? localStorage.getItem("mhb_token") : "";
        return { Authorization: `Bearer ${token}` };
    };

    async function loadStats() {
        setLoading(true);
        try {
            const res = await fetch(`${API}/api/stats`, { headers: authHeaders() });
            if (res.ok) setStats(await res.json());
        } catch (e) { console.error(e); }
        setLoading(false);
    }

    useEffect(() => { loadStats(); }, []);

    const healthItems = stats ? [
        { label: "FFmpeg", value: stats.health?.ffmpeg, ok: stats.health?.ffmpeg !== "Not found", icon: Zap },
        { label: "7-Zip", value: stats.health?.sevenZip, ok: stats.health?.sevenZip !== "Not found", icon: Database },
        { label: "Redis", value: stats.health?.redis ? "Connected" : "Disconnected", ok: stats.health?.redis, icon: Database },
    ] : [];

    const storageItems = stats ? [
        { label: "Downloads", value: stats.storage?.downloads?.sizeHuman, icon: HardDrive },
        { label: "Extracted", value: stats.storage?.extracted?.sizeHuman, icon: HardDrive },
        { label: "Output", value: stats.storage?.output?.sizeHuman, icon: HardDrive },
        { label: "Temp", value: stats.storage?.temp?.sizeHuman, icon: HardDrive },
        { label: "Total Used", value: stats.storage?.total?.sizeHuman, icon: HardDrive },
    ] : [];

    return (
        <div className="space-y-8 max-w-2xl mx-auto pb-20">
            <div className="flex items-center justify-between">
                <div className="flex items-center gap-4">
                    <div className="w-12 h-12 rounded-2xl bg-emerald-500/10 flex items-center justify-center">
                        <HeartPulse className="w-6 h-6 text-emerald-400" />
                    </div>
                    <div>
                        <h1 className="text-2xl font-extrabold text-white">System Health</h1>
                        <p className="text-white/40 text-sm">FFmpeg, Redis, disk usage, and storage breakdown.</p>
                    </div>
                </div>
                <button onClick={loadStats} disabled={loading} className="btn-ghost py-2 px-4 flex items-center gap-2 text-sm">
                    <RefreshCcw className={`w-4 h-4 ${loading ? "animate-spin" : ""}`} /> Refresh
                </button>
            </div>

            {loading ? (
                <div className="flex justify-center py-20"><Loader2 className="w-8 h-8 animate-spin text-accent-cyan" /></div>
            ) : (
                <>
                    {/* Services */}
                    <div className="card p-6 bg-black/40 border-white/10">
                        <h2 className="text-sm font-black uppercase tracking-widest text-white/40 mb-4">Services</h2>
                        <div className="space-y-3">
                            {healthItems.map(item => (
                                <div key={item.label} className="flex items-center justify-between p-3 rounded-xl bg-white/5">
                                    <div className="flex items-center gap-3">
                                        {item.ok ? <CheckCircle2 className="w-5 h-5 text-emerald-400" /> : <XCircle className="w-5 h-5 text-red-400" />}
                                        <span className="font-bold text-white text-sm">{item.label}</span>
                                    </div>
                                    <span className="text-xs text-white/40 font-mono max-w-[60%] text-right truncate">{item.value}</span>
                                </div>
                            ))}
                        </div>
                    </div>

                    {/* Disk */}
                    {stats?.disk?.total > 0 && (
                        <div className="card p-6 bg-black/40 border-white/10">
                            <h2 className="text-sm font-black uppercase tracking-widest text-white/40 mb-4">Disk Usage</h2>
                            <div className="flex items-center justify-between text-sm mb-2">
                                <span className="text-white/60">Used: {stats.disk.usedHuman}</span>
                                <span className={stats.disk.usedPercent > 85 ? "text-red-400 font-black" : "text-white/60"}>
                                    {stats.disk.usedPercent}%
                                </span>
                                <span className="text-white/60">Free: {stats.disk.availHuman}</span>
                            </div>
                            <div className="w-full bg-white/5 h-3 rounded-full overflow-hidden">
                                <div
                                    className={`h-full rounded-full transition-all ${stats.disk.usedPercent > 85 ? "bg-red-500" : stats.disk.usedPercent > 70 ? "bg-amber-500" : "bg-emerald-500"}`}
                                    style={{ width: `${stats.disk.usedPercent}%` }}
                                />
                            </div>
                            <p className="text-xs text-white/30 mt-2">Total: {stats.disk.totalHuman}</p>
                        </div>
                    )}

                    {/* Storage Breakdown */}
                    <div className="card p-6 bg-black/40 border-white/10">
                        <h2 className="text-sm font-black uppercase tracking-widest text-white/40 mb-4">Storage Breakdown</h2>
                        <div className="divide-y divide-white/5">
                            {storageItems.map(item => (
                                <div key={item.label} className="flex items-center justify-between py-3">
                                    <span className="text-white/60 text-sm">{item.label}</span>
                                    <span className="text-white font-bold text-sm">{item.value || "0 B"}</span>
                                </div>
                            ))}
                        </div>
                    </div>

                    {/* Job Stats */}
                    {stats?.jobs && (
                        <div className="card p-6 bg-black/40 border-white/10">
                            <h2 className="text-sm font-black uppercase tracking-widest text-white/40 mb-4">Job Statistics</h2>
                            <div className="grid grid-cols-3 gap-3">
                                {[
                                    { label: "Total", value: stats.jobs.total, color: "text-white" },
                                    { label: "Completed", value: stats.jobs.completed, color: "text-emerald-400" },
                                    { label: "Failed", value: stats.jobs.failed, color: "text-red-400" },
                                    { label: "Active", value: stats.jobs.processing, color: "text-blue-400" },
                                    { label: "Pending", value: stats.jobs.pending, color: "text-amber-400" },
                                    { label: "Cancelled", value: stats.jobs.cancelled, color: "text-white/40" },
                                ].map(s => (
                                    <div key={s.label} className="bg-white/5 rounded-xl p-3 text-center">
                                        <p className="text-[9px] uppercase font-black tracking-widest text-white/30 mb-1">{s.label}</p>
                                        <p className={`text-2xl font-black ${s.color}`}>{s.value}</p>
                                    </div>
                                ))}
                            </div>
                        </div>
                    )}

                    <p className="text-xs text-white/20 text-center">Last updated: {stats?.timestamp ? new Date(stats.timestamp).toLocaleString() : "—"}</p>
                </>
            )}
        </div>
    );
}
