"use client";

import { useState, useEffect, useCallback } from "react";
import {
  Users, Zap, TrendingUp, Activity,
  RefreshCw, Loader2, BarChart2, ArrowUpRight, ArrowDownRight,
} from "lucide-react";
import { cn } from "@/lib/utils";
import { PLATFORM_CONFIGS } from "@/types";

// ─── Types ────────────────────────────────────────────────────────────────────
interface StatsData {
  users: { total: number; new_today: number; new_7d: number };
  generations: { total: number; today: number; last_7d: number };
  per_platform: Record<string, number>;
  chart: { date: string; count: number; platforms: Record<string, number> }[];
  top_users: Array<{
    id: string; email: string; full_name: string | null;
    usage_count: number; plan: string; role: string;
  }>;
  fetched_at: string;
}

const PLATFORM_COLORS: Record<string, string> = {
  seedance:     "#8b5cf6",
  gemini_omni:  "#3b82f6",
  kling_motion: "#f97316",
  higgsfield:   "#14b8a6",
  tiktok_ugc:   "#ec4899",
};

// ─── KPI Card ─────────────────────────────────────────────────────────────────
function KpiCard({
  icon, title, value, sub, trend, accent,
}: {
  icon: React.ReactNode;
  title: string;
  value: string | number;
  sub?: string;
  trend?: number;
  accent: string;
}) {
  return (
    <div
      className="rounded-2xl p-5 relative overflow-hidden"
      style={{
        background: `linear-gradient(135deg, ${accent}18, ${accent}08)`,
        border: `1px solid ${accent}28`,
      }}
    >
      <div
        className="absolute -top-5 -right-5 w-20 h-20 rounded-full opacity-15 blur-2xl"
        style={{ background: accent }}
      />
      <div className="flex items-start justify-between mb-3">
        <div className="w-10 h-10 rounded-xl flex items-center justify-center"
          style={{ background: `${accent}20` }}>
          <span style={{ color: accent }}>{icon}</span>
        </div>
        {trend !== undefined && (
          <span className={cn("flex items-center gap-0.5 text-xs font-medium",
            trend >= 0 ? "text-emerald-400" : "text-red-400")}>
            {trend >= 0 ? <ArrowUpRight className="w-3.5 h-3.5" /> : <ArrowDownRight className="w-3.5 h-3.5" />}
            {Math.abs(trend)}%
          </span>
        )}
      </div>
      <p className="text-2xl font-bold tabular-nums">{typeof value === "number" ? value.toLocaleString() : value}</p>
      <p className="text-sm font-medium mt-0.5">{title}</p>
      {sub && <p className="text-xs text-muted-foreground mt-0.5">{sub}</p>}
    </div>
  );
}

// ─── Mini Bar Chart ───────────────────────────────────────────────────────────
function MiniBarChart({ data }: { data: { date: string; count: number }[] }) {
  const max = Math.max(...data.map((d) => d.count), 1);
  return (
    <div className="flex items-end gap-1 h-20">
      {data.map((d) => (
        <div key={d.date} className="flex-1 group relative flex flex-col justify-end">
          <div
            className="w-full rounded-t transition-all"
            style={{
              height: `${Math.max((d.count / max) * 100, 4)}%`,
              minHeight: 2,
              background: "linear-gradient(180deg, rgba(212,175,55,0.8), rgba(212,175,55,0.3))",
              boxShadow: "0 -2px 6px rgba(212,175,55,0.2)",
            }}
          />
          {/* Tooltip */}
          <div className="absolute bottom-full mb-1.5 left-1/2 -translate-x-1/2 bg-card rounded-lg px-2 py-1 text-[10px] whitespace-nowrap opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none z-10 shadow-lg"
            style={{ border: "1px solid rgba(212,175,55,0.25)" }}>
            {d.date.slice(5)}: <strong className="text-amber-300">{d.count}</strong>
          </div>
        </div>
      ))}
    </div>
  );
}

// ─── Main ─────────────────────────────────────────────────────────────────────
export default function AdminDashboardPage() {
  const [stats, setStats] = useState<StatsData | null>(null);
  const [loading, setLoading] = useState(true);
  const [lastRefresh, setLastRefresh] = useState<Date | null>(null);
  const [autoRefresh, setAutoRefresh] = useState(true);

  const fetchStats = useCallback(async () => {
    try {
      const res = await fetch("/api/admin/stats");
      if (!res.ok) return;
      const data = await res.json();
      setStats(data);
      setLastRefresh(new Date());
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => { fetchStats(); }, [fetchStats]);
  useEffect(() => {
    if (!autoRefresh) return;
    const t = setInterval(fetchStats, 30_000);
    return () => clearInterval(t);
  }, [autoRefresh, fetchStats]);

  const totalPlatformGen = Object.values(stats?.per_platform ?? {}).reduce((a, b) => a + b, 0);

  return (
    <div className="max-w-7xl mx-auto space-y-6">

      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold">Live Dashboard</h1>
          <p className="text-xs text-muted-foreground mt-0.5">
            {lastRefresh
              ? `Terakhir diperbarui: ${lastRefresh.toLocaleTimeString("id-ID")}`
              : "Memuat data..."}
          </p>
        </div>
        <div className="flex items-center gap-2">
          <button
            onClick={() => setAutoRefresh(!autoRefresh)}
            className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium transition-all"
            style={
              autoRefresh
                ? { background: "rgba(212,175,55,0.12)", border: "1px solid rgba(212,175,55,0.25)", color: "#d4af37" }
                : { background: "rgba(255,255,255,0.05)", border: "1px solid rgba(255,255,255,0.1)", color: "hsl(var(--muted-foreground))" }
            }
          >
            <span className={cn("w-1.5 h-1.5 rounded-full", autoRefresh ? "bg-amber-400 animate-pulse" : "bg-muted-foreground")} />
            {autoRefresh ? "Live (30s)" : "Paused"}
          </button>
          <button
            onClick={fetchStats}
            disabled={loading}
            className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-sm transition-all hover:bg-white/5 disabled:opacity-50"
            style={{ border: "1px solid rgba(212,175,55,0.2)" }}
          >
            <RefreshCw className={cn("w-3.5 h-3.5", loading && "animate-spin")} />
            Refresh
          </button>
        </div>
      </div>

      {loading && !stats ? (
        <div className="flex items-center justify-center py-24">
          <Loader2 className="w-8 h-8 animate-spin text-amber-400/50" />
        </div>
      ) : stats ? (
        <>
          {/* KPI Cards */}
          <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
            <KpiCard icon={<Users className="w-5 h-5" />} title="Total User"
              value={stats.users.total} sub={`+${stats.users.new_today} hari ini`} accent="#3b82f6" />
            <KpiCard icon={<Zap className="w-5 h-5" />} title="Total Generasi"
              value={stats.generations.total} sub={`${stats.generations.today} hari ini`} accent="#8b5cf6" />
            <KpiCard icon={<TrendingUp className="w-5 h-5" />} title="Generasi 7 Hari"
              value={stats.generations.last_7d} sub={`~${Math.round(stats.generations.last_7d / 7)} per hari`} accent="#06b6d4" />
            <KpiCard icon={<Activity className="w-5 h-5" />} title="User Baru 7 Hari"
              value={stats.users.new_7d} sub={`+${stats.users.new_today} hari ini`} accent="#d4af37" />
          </div>

          {/* Chart + Platform */}
          <div className="grid lg:grid-cols-3 gap-4">

            {/* Bar chart */}
            <div className="gold-card rounded-2xl p-5 lg:col-span-2">
              <div className="flex items-center justify-between mb-5">
                <div>
                  <h2 className="font-semibold">Generasi 14 Hari Terakhir</h2>
                  <p className="text-xs text-muted-foreground mt-0.5">Hover bar untuk detail</p>
                </div>
                <BarChart2 className="w-5 h-5 text-amber-400/50" />
              </div>
              <MiniBarChart data={stats.chart} />
              <div className="gold-hr-soft mt-4 mb-3" />
              <div className="flex gap-5 text-xs text-muted-foreground">
                <span>Min: <strong className="text-foreground">{Math.min(...stats.chart.map((d) => d.count))}</strong></span>
                <span>Max: <strong className="text-foreground">{Math.max(...stats.chart.map((d) => d.count))}</strong></span>
                <span>Total: <strong className="text-foreground">{stats.chart.reduce((a, d) => a + d.count, 0)}</strong></span>
              </div>
            </div>

            {/* Platform breakdown */}
            <div className="gold-card rounded-2xl p-5">
              <h2 className="font-semibold mb-4">Platform Breakdown</h2>
              <div className="space-y-3.5">
                {Object.entries(PLATFORM_CONFIGS).map(([id, cfg]) => {
                  const count = stats.per_platform[id] ?? 0;
                  const pct = totalPlatformGen > 0 ? Math.round((count / totalPlatformGen) * 100) : 0;
                  const color = PLATFORM_COLORS[id] ?? "#7c3aed";
                  return (
                    <div key={id}>
                      <div className="flex items-center justify-between text-sm mb-1.5">
                        <span className="flex items-center gap-1.5 text-xs">
                          <span>{cfg.icon}</span> {cfg.name}
                        </span>
                        <span className="tabular-nums text-xs font-medium">
                          {count.toLocaleString()}{" "}
                          <span className="text-muted-foreground">({pct}%)</span>
                        </span>
                      </div>
                      <div className="h-1.5 rounded-full overflow-hidden"
                        style={{ background: "rgba(255,255,255,0.06)" }}>
                        <div
                          className="h-full rounded-full transition-all duration-500"
                          style={{ width: `${pct}%`, background: color, boxShadow: `0 0 6px ${color}60` }}
                        />
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>
          </div>

          {/* Top Users */}
          <div className="gold-card rounded-2xl p-5">
            <div className="flex items-center gap-3 mb-4">
              <h2 className="font-semibold">Top 5 Pengguna Paling Aktif</h2>
              <div className="flex-1 gold-hr-soft" />
            </div>
            <table className="w-full text-sm">
              <thead>
                <tr className="text-xs text-muted-foreground">
                  <th className="text-left pb-3 font-medium">#</th>
                  <th className="text-left pb-3 font-medium">User</th>
                  <th className="text-left pb-3 font-medium">Plan</th>
                  <th className="text-left pb-3 font-medium">Role</th>
                  <th className="text-right pb-3 font-medium">Generasi</th>
                </tr>
              </thead>
              <tbody>
                {stats.top_users.map((u, i) => (
                  <tr key={u.id} className="hover:bg-white/3 transition-colors"
                    style={{ borderTop: "1px solid rgba(212,175,55,0.07)" }}>
                    <td className="py-2.5 text-muted-foreground text-xs">
                      {i === 0 ? "🥇" : i === 1 ? "🥈" : i === 2 ? "🥉" : i + 1}
                    </td>
                    <td className="py-2.5">
                      <p className="font-medium">{u.full_name ?? "—"}</p>
                      <p className="text-xs text-muted-foreground">{u.email}</p>
                    </td>
                    <td className="py-2.5">
                      <span className={cn(
                        "text-xs px-2 py-0.5 rounded-full",
                        u.plan === "pro" ? "bg-purple-500/20 text-purple-300"
                        : u.plan === "enterprise" ? "bg-amber-500/20 text-amber-300"
                        : "bg-white/8 text-muted-foreground"
                      )}>
                        {u.plan}
                      </span>
                    </td>
                    <td className="py-2.5">
                      {u.role === "admin"
                        ? <span className="text-xs px-2 py-0.5 rounded-full bg-amber-500/15 text-amber-400">admin</span>
                        : <span className="text-xs text-muted-foreground">user</span>}
                    </td>
                    <td className="py-2.5 text-right font-bold tabular-nums text-amber-300">
                      {u.usage_count.toLocaleString()}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </>
      ) : null}
    </div>
  );
}
