"use client"

import { useState, useEffect, useCallback } from "react"
import {
  AreaChart, Area,
  BarChart, Bar,
  LineChart, Line,
  PieChart, Pie, Cell,
  ComposedChart,
  XAxis, YAxis, CartesianGrid,
  Tooltip, Legend, ResponsiveContainer,
} from "recharts"
import {
  Building2, Users, Shield, Activity,
  TrendingUp, TrendingDown, ArrowUpRight,
  Globe, Zap, AlertTriangle, CheckCircle2,
  Clock, RefreshCw, ChevronRight, Server,
  CreditCard, UserCheck, BarChart3, Settings,
  Circle,
} from "lucide-react"
import Link from "next/link"
import { useLocale } from "next-intl"
import {
  getAdminDashboardStats,
  type AdminDashboardStats,
  type DashboardPeriod,
} from "@/src/lib/api/admin"

// ── Palette ACX ────────────────────────────────────────────────────────────
const NAVY   = "#1a3578"
const NAVY2  = "#2655b0"
const TEAL   = "#4dba96"
const TEAL2  = "#2d9073"
const AMBER  = "#f59e0b"
const RED    = "#ef4444"
const SLATE  = "#64748b"

const PLAN_COLORS: Record<string, string> = {
  enterprise: NAVY,
  business:   TEAL,
  starter:    AMBER,
  autre:      SLATE,
}

function cx(...c: (string | false | null | undefined)[]) {
  return c.filter(Boolean).join(" ")
}

function fmt(n: number) {
  if (n >= 1_000_000) return (n / 1_000_000).toFixed(1) + "M"
  if (n >= 1_000)     return (n / 1_000).toFixed(0) + "k"
  return String(n)
}

function pctDelta(current: number, prev: number) {
  if (!prev) return null
  return (((current - prev) / prev) * 100).toFixed(1) + "%"
}

// ── Tooltip personnalisé ────────────────────────────────────────────────────
function CustomTooltip({ active, payload, label }: any) {
  if (!active || !payload?.length) return null
  return (
    <div className="rounded-xl border bg-white px-3.5 py-3 shadow-xl text-xs min-w-[140px]">
      <p className="font-semibold text-slate-700 mb-2">{label}</p>
      {payload.map((p: any) => (
        <div key={p.name} className="flex items-center justify-between gap-4">
          <span className="flex items-center gap-1.5 text-slate-500">
            <span className="inline-block h-2 w-2 rounded-full" style={{ backgroundColor: p.color }} />
            {p.name}
          </span>
          <span className="font-semibold text-slate-800">
            {typeof p.value === "number" && p.value > 1000 ? fmt(p.value) : p.value}
          </span>
        </div>
      ))}
    </div>
  )
}

// ── KPI card ───────────────────────────────────────────────────────────────
function KpiCard({
  label, value, delta, deltaUp, hint, icon: Icon, accent, loading,
}: {
  label: string; value: string; delta?: string | null; deltaUp?: boolean
  hint?: string; icon: any; accent: string; loading?: boolean
}) {
  return (
    <div className="rounded-2xl border bg-white p-5 shadow-sm hover:shadow-md transition-shadow">
      <div className="flex items-start justify-between gap-3">
        <div className="flex-1 min-w-0">
          <p className="text-xs font-semibold uppercase tracking-widest text-slate-400">{label}</p>
          {loading ? (
            <div className="mt-2 h-9 w-24 rounded-lg bg-slate-100 animate-pulse" />
          ) : (
            <p className="mt-2 text-3xl font-bold text-slate-900 tracking-tight">{value}</p>
          )}
          {!loading && delta && (
            <div className="mt-2 flex items-center gap-1.5">
              <span
                className="inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-[11px] font-semibold ring-1"
                style={{
                  color:       deltaUp ? "#059669" : "#dc2626",
                  background:  deltaUp ? "rgba(5,150,105,0.08)" : "rgba(220,38,38,0.08)",
                  borderColor: deltaUp ? "rgba(5,150,105,0.20)" : "rgba(220,38,38,0.20)",
                }}
              >
                {deltaUp ? <TrendingUp className="h-3 w-3" /> : <TrendingDown className="h-3 w-3" />}
                {delta}
              </span>
              {hint && <span className="text-[11px] text-slate-400">{hint}</span>}
            </div>
          )}
        </div>
        <div
          className="flex h-12 w-12 shrink-0 items-center justify-center rounded-2xl ring-1"
          style={{ background: `${accent}14`, borderColor: `${accent}28` }}
        >
          <Icon className="h-5 w-5" style={{ color: accent }} />
        </div>
      </div>
    </div>
  )
}

// ── Barre de section ───────────────────────────────────────────────────────
function SectionHeader({ title, sub, action }: { title: string; sub?: string; action?: React.ReactNode }) {
  return (
    <div className="flex items-end justify-between gap-4 mb-4">
      <div>
        <h2 className="text-[15px] font-semibold text-slate-800">{title}</h2>
        {sub && <p className="text-xs text-slate-400 mt-0.5">{sub}</p>}
      </div>
      {action}
    </div>
  )
}

// ── Skeleton ligne ─────────────────────────────────────────────────────────
function SkeletonRow() {
  return (
    <tr>
      {[1,2,3,4,5,6].map((i) => (
        <td key={i} className="px-3 py-3">
          <div className="h-4 rounded bg-slate-100 animate-pulse" style={{ width: `${50 + i * 10}%` }} />
        </td>
      ))}
    </tr>
  )
}

// ── Helpers statut tenant ──────────────────────────────────────────────────
const statusColor  = (s: string) => s === "active" ? "#059669" : s === "warning" ? "#f59e0b" : "#94a3b8"
const statusBg     = (s: string) => s === "active" ? "rgba(5,150,105,0.08)" : s === "warning" ? "rgba(245,158,11,0.08)" : "rgba(148,163,184,0.08)"
const statusLabel  = (s: string) => s === "active" ? "Actif" : s === "suspended" ? "Suspendu" : "Inactif"
const levelColor   = (l: string) => l === "error" ? RED : l === "warn" ? AMBER : TEAL

// ── Page principale ────────────────────────────────────────────────────────
export default function AdminDashboardPage() {
  const locale = useLocale()
  const [period, setPeriod]   = useState<DashboardPeriod>("30d")
  const [stats, setStats]     = useState<AdminDashboardStats | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError]     = useState<string | null>(null)

  const fetchStats = useCallback(async () => {
    setLoading(true)
    setError(null)
    try {
      const data = await getAdminDashboardStats(period)
      setStats(data)
    } catch (e: any) {
      setError(e?.message ?? "Erreur lors du chargement des statistiques")
    } finally {
      setLoading(false)
    }
  }, [period])

  useEffect(() => { fetchStats() }, [fetchStats])

  const kpis  = stats?.kpis
  const growth = stats?.growth ?? []
  const planDist = (stats?.plan_distribution ?? []).map((p) => ({
    ...p,
    color: PLAN_COLORS[(p.name || "").toLowerCase()] ?? SLATE,
  }))
  const tenantHealth = stats?.tenant_health ?? []
  const auditLog     = stats?.audit_log     ?? []

  const totalMRR  = kpis?.total_mrr ?? 0
  const totalCases = kpis?.total_cases ?? 0
  const firstCases = growth[0]?.cases ?? 0
  const lastCases  = growth[growth.length - 1]?.cases ?? 0
  const casesDelta = pctDelta(lastCases, firstCases)

  const tenantDelta = kpis
    ? pctDelta(kpis.total_tenants, kpis.prev_tenants)
    : null
  const userDelta = kpis
    ? pctDelta(kpis.total_users, kpis.prev_users)
    : null

  const planTotal = planDist.reduce((s, p) => s + p.value, 0)

  return (
    <div className="space-y-8 pb-8">

      {/* ── En-tête ────────────────────────────────────────────────────── */}
      <div className="flex flex-col gap-4 sm:flex-row sm:items-end sm:justify-between">
        <div>
          <div className="flex items-center gap-2 mb-1">
            <div className="h-2 w-2 rounded-full animate-pulse" style={{ backgroundColor: TEAL }} />
            <span className="text-xs font-medium text-slate-400 uppercase tracking-wider">Super Admin</span>
          </div>
          <h1 className="text-2xl font-bold text-slate-900">Vue globale de la plateforme</h1>
          <p className="text-sm text-slate-500 mt-1">
            Pilotage en temps réel ·{" "}
            {new Date().toLocaleDateString("fr-FR", { weekday: "long", day: "numeric", month: "long", year: "numeric" })}
          </p>
        </div>

        <div className="flex items-center gap-2">
          {/* Sélecteur de période */}
          <div className="flex items-center gap-1 rounded-xl border bg-white p-1 shadow-sm">
            {(["7d", "30d", "90d", "12m"] as DashboardPeriod[]).map((p) => (
              <button
                key={p}
                onClick={() => setPeriod(p)}
                className={cx(
                  "rounded-lg px-3 py-1.5 text-xs font-semibold transition-all",
                  period === p ? "text-white shadow-sm" : "text-slate-500 hover:text-slate-700",
                )}
                style={period === p ? { backgroundColor: NAVY } : {}}
              >
                {p}
              </button>
            ))}
          </div>

          {/* Actualiser */}
          <button
            onClick={fetchStats}
            disabled={loading}
            className="flex items-center gap-1.5 rounded-xl border bg-white px-3.5 py-2 shadow-sm text-xs font-medium text-slate-600 hover:bg-slate-50 transition disabled:opacity-50"
          >
            <RefreshCw className={cx("h-3.5 w-3.5", loading && "animate-spin")} />
            Actualiser
          </button>
        </div>
      </div>

      {/* ── Erreur ─────────────────────────────────────────────────────── */}
      {error && (
        <div className="rounded-xl border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700 flex items-center gap-2">
          <AlertTriangle className="h-4 w-4 shrink-0" />
          {error}
        </div>
      )}

      {/* ── KPIs ───────────────────────────────────────────────────────── */}
      <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-4 gap-4">
        <KpiCard
          label="Tenants actifs"
          value={kpis ? String(kpis.total_tenants) : "—"}
          delta={tenantDelta}
          deltaUp={(kpis?.total_tenants ?? 0) >= (kpis?.prev_tenants ?? 0)}
          hint="vs mois dernier"
          icon={Building2}
          accent={NAVY}
          loading={loading}
        />
        <KpiCard
          label="Utilisateurs"
          value={kpis ? String(kpis.total_users) : "—"}
          delta={userDelta}
          deltaUp={(kpis?.total_users ?? 0) >= (kpis?.prev_users ?? 0)}
          hint="vs mois dernier"
          icon={Users}
          accent={TEAL}
          loading={loading}
        />
        <KpiCard
          label="Dossiers actifs"
          value={kpis ? fmt(kpis.total_cases) : "—"}
          delta={casesDelta}
          deltaUp={(lastCases) >= firstCases}
          hint="sur la période"
          icon={BarChart3}
          accent={NAVY2}
          loading={loading}
        />
        <KpiCard
          label="MRR estimé"
          value={kpis ? `${fmt(totalMRR)} FCFA` : "—"}
          icon={CreditCard}
          accent={TEAL2}
          loading={loading}
        />
      </div>

      {/* ── Croissance + Répartition plans ─────────────────────────────── */}
      <div className="grid grid-cols-1 xl:grid-cols-3 gap-4">

        {/* Courbe de croissance */}
        <div className="xl:col-span-2 rounded-2xl border bg-white p-5 shadow-sm">
          <SectionHeader
            title="Croissance de la plateforme"
            sub="Tenants, utilisateurs et dossiers sur la période sélectionnée"
            action={
              <span className="text-[11px] font-medium rounded-lg px-2.5 py-1 ring-1"
                style={{ color: NAVY, background: `${NAVY}0d`, borderColor: `${NAVY}20` }}>
                {period.toUpperCase()}
              </span>
            }
          />
          {loading ? (
            <div className="h-[280px] rounded-xl bg-slate-100 animate-pulse" />
          ) : (
            <div className="h-[280px]">
              <ResponsiveContainer width="100%" height="100%">
                <ComposedChart data={growth} margin={{ left: -10, right: 10 }}>
                  <defs>
                    <linearGradient id="gTenants" x1="0" y1="0" x2="0" y2="1">
                      <stop offset="5%"  stopColor={NAVY} stopOpacity={0.18} />
                      <stop offset="95%" stopColor={NAVY} stopOpacity={0} />
                    </linearGradient>
                    <linearGradient id="gUsers" x1="0" y1="0" x2="0" y2="1">
                      <stop offset="5%"  stopColor={TEAL} stopOpacity={0.18} />
                      <stop offset="95%" stopColor={TEAL} stopOpacity={0} />
                    </linearGradient>
                  </defs>
                  <CartesianGrid strokeDasharray="3 3" stroke="#f1f5f9" />
                  <XAxis dataKey="name" tick={{ fontSize: 11, fill: "#94a3b8" }} axisLine={false} tickLine={false} />
                  <YAxis yAxisId="left"  tick={{ fontSize: 11, fill: "#94a3b8" }} axisLine={false} tickLine={false} />
                  <YAxis yAxisId="right" orientation="right" tick={{ fontSize: 11, fill: "#94a3b8" }} axisLine={false} tickLine={false} />
                  <Tooltip content={<CustomTooltip />} />
                  <Legend iconType="circle" iconSize={8} wrapperStyle={{ fontSize: 12 }} />
                  <Area yAxisId="right" type="monotone" dataKey="users"   name="Utilisateurs" stroke={TEAL}  strokeWidth={2} fill="url(#gUsers)"   dot={false} />
                  <Area yAxisId="right" type="monotone" dataKey="cases"   name="Dossiers"     stroke={NAVY2} strokeWidth={2} fill="url(#gTenants)" dot={false} />
                  <Bar  yAxisId="left"  dataKey="tenants" name="Tenants"  fill={NAVY} fillOpacity={0.85} radius={[4,4,0,0]} maxBarSize={24} />
                </ComposedChart>
              </ResponsiveContainer>
            </div>
          )}
        </div>

        {/* Répartition par plan */}
        <div className="rounded-2xl border bg-white p-5 shadow-sm">
          <SectionHeader title="Répartition par plan" sub="Distribution actuelle des tenants" />
          {loading ? (
            <div className="h-[200px] rounded-xl bg-slate-100 animate-pulse" />
          ) : planDist.length === 0 ? (
            <div className="h-[200px] flex items-center justify-center text-sm text-slate-400">
              Aucune donnée
            </div>
          ) : (
            <>
              <div className="h-[200px]">
                <ResponsiveContainer width="100%" height="100%">
                  <PieChart>
                    <Tooltip content={<CustomTooltip />} />
                    <Pie
                      data={planDist}
                      dataKey="value"
                      nameKey="name"
                      cx="50%" cy="50%"
                      innerRadius={55} outerRadius={85}
                      paddingAngle={3} strokeWidth={0}
                    >
                      {planDist.map((entry) => (
                        <Cell key={entry.name} fill={entry.color} />
                      ))}
                    </Pie>
                  </PieChart>
                </ResponsiveContainer>
              </div>
              <div className="mt-2 space-y-2">
                {planDist.map((p) => (
                  <div key={p.name} className="flex items-center justify-between">
                    <div className="flex items-center gap-2">
                      <span className="h-2.5 w-2.5 rounded-full shrink-0" style={{ backgroundColor: p.color }} />
                      <span className="text-sm text-slate-600">{p.name}</span>
                    </div>
                    <div className="flex items-center gap-2">
                      <span className="text-sm font-semibold text-slate-800">{p.value}</span>
                      <span className="text-xs text-slate-400">
                        {planTotal ? Math.round(p.value / planTotal * 100) : 0}%
                      </span>
                    </div>
                  </div>
                ))}
              </div>
            </>
          )}
        </div>
      </div>

      {/* ── Santé des tenants + Audit log ──────────────────────────────── */}
      <div className="grid grid-cols-1 xl:grid-cols-3 gap-4">

        {/* Tableau des tenants */}
        <div className="xl:col-span-2 rounded-2xl border bg-white shadow-sm overflow-hidden">
          <div className="px-5 pt-5 pb-3">
            <SectionHeader
              title="Santé des tenants"
              sub="Dossiers, utilisateurs, plan et statut"
              action={
                <Link
                  href={`/${locale}/admin/tenants`}
                  className="flex items-center gap-1 text-[11px] font-medium transition hover:underline underline-offset-2"
                  style={{ color: NAVY }}
                >
                  Voir tous <ChevronRight className="h-3 w-3" />
                </Link>
              }
            />
          </div>
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr className="border-y bg-slate-50/60">
                  {["Tenant", "Dossiers", "Users", "Plan", "MRR", "Statut"].map((h, i) => (
                    <th
                      key={h}
                      className={cx(
                        "py-2.5 text-[11px] font-semibold uppercase tracking-wider text-slate-400",
                        i === 0 ? "px-5 text-left" : i < 5 ? "px-3 text-right" : "px-5 text-left",
                      )}
                    >
                      {h}
                    </th>
                  ))}
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-50">
                {loading
                  ? [1,2,3,4,5].map((i) => <SkeletonRow key={i} />)
                  : tenantHealth.length === 0
                  ? (
                    <tr>
                      <td colSpan={6} className="px-5 py-8 text-center text-sm text-slate-400">
                        Aucun tenant
                      </td>
                    </tr>
                  )
                  : tenantHealth.map((t) => (
                    <tr key={t.id} className="group hover:bg-slate-50/60 transition-colors">
                      <td className="px-5 py-3">
                        <div className="flex items-center gap-2.5">
                          <div
                            className="flex h-8 w-8 shrink-0 items-center justify-center rounded-xl text-[11px] font-bold text-white"
                            style={{ backgroundColor: NAVY }}
                          >
                            {t.name.slice(0, 2).toUpperCase()}
                          </div>
                          <span className="font-medium text-slate-800">{t.name}</span>
                        </div>
                      </td>
                      <td className="px-3 py-3 text-right font-semibold text-slate-700">{t.cases}</td>
                      <td className="px-3 py-3 text-right text-slate-500">{t.users}</td>
                      <td className="px-3 py-3">
                        {t.plan ? (
                          <span
                            className="rounded-full px-2.5 py-0.5 text-[11px] font-semibold ring-1"
                            style={{
                              color:       PLAN_COLORS[t.plan.toLowerCase()] ?? SLATE,
                              background:  `${PLAN_COLORS[t.plan.toLowerCase()] ?? SLATE}10`,
                              borderColor: `${PLAN_COLORS[t.plan.toLowerCase()] ?? SLATE}25`,
                            }}
                          >
                            {t.plan}
                          </span>
                        ) : (
                          <span className="text-slate-400 text-xs">—</span>
                        )}
                      </td>
                      <td className="px-3 py-3 text-right text-slate-600 font-medium">
                        {t.mrr ? fmt(t.mrr) : "—"}
                      </td>
                      <td className="px-5 py-3">
                        <span
                          className="flex items-center gap-1.5 rounded-full px-2.5 py-0.5 text-[11px] font-semibold ring-1 w-fit"
                          style={{
                            color:       statusColor(t.status),
                            background:  statusBg(t.status),
                            borderColor: `${statusColor(t.status)}30`,
                          }}
                        >
                          <Circle className="h-1.5 w-1.5 fill-current" />
                          {statusLabel(t.status)}
                        </span>
                      </td>
                    </tr>
                  ))
                }
              </tbody>
            </table>
          </div>
        </div>

        {/* Audit log */}
        <div className="rounded-2xl border bg-white p-5 shadow-sm">
          <SectionHeader
            title="Journal d'audit"
            sub="Actions récentes sur la plateforme"
            action={
              <span className="text-[11px] text-slate-400 flex items-center gap-1">
                <Clock className="h-3 w-3" /> Récent
              </span>
            }
          />
          <div className="space-y-1">
            {loading
              ? [1,2,3,4,5].map((i) => (
                <div key={i} className="flex items-start gap-3 rounded-xl px-3 py-2.5">
                  <div className="h-7 w-7 shrink-0 rounded-lg bg-slate-100 animate-pulse" />
                  <div className="flex-1 space-y-1">
                    <div className="h-3 rounded bg-slate-100 animate-pulse w-4/5" />
                    <div className="h-2.5 rounded bg-slate-100 animate-pulse w-1/2" />
                  </div>
                </div>
              ))
              : auditLog.length === 0
              ? (
                <p className="py-4 text-center text-sm text-slate-400">Aucune activité récente</p>
              )
              : auditLog.map((e, i) => {
                const level = e.actor === "system" ? "warn" : "info"
                const label = e.entity_label
                  ? `${e.action} — ${e.entity_label}`
                  : e.action
                const time = new Date(e.created_at).toLocaleTimeString("fr-FR", {
                  hour: "2-digit", minute: "2-digit",
                })
                return (
                  <div
                    key={i}
                    className="flex items-start gap-3 rounded-xl px-3 py-2.5 hover:bg-slate-50 transition-colors"
                  >
                    <div
                      className="mt-0.5 flex h-7 w-7 shrink-0 items-center justify-center rounded-lg ring-1"
                      style={{
                        background:  `${levelColor(level)}10`,
                        borderColor: `${levelColor(level)}25`,
                      }}
                    >
                      <Activity className="h-3.5 w-3.5" style={{ color: levelColor(level) }} />
                    </div>
                    <div className="flex-1 min-w-0">
                      <p className="text-xs font-medium text-slate-700 leading-snug truncate">{label}</p>
                      <p className="text-[10px] text-slate-400 mt-0.5">
                        {e.actor}{e.tenant ? ` · ${e.tenant}` : ""}
                      </p>
                    </div>
                    <span className="text-[10px] text-slate-400 shrink-0 mt-0.5">{time}</span>
                  </div>
                )
              })
            }
          </div>

          <button
            onClick={fetchStats}
            className="mt-4 w-full rounded-xl border py-2 text-xs font-semibold transition hover:bg-slate-50 flex items-center justify-center gap-1.5"
            style={{ color: NAVY, borderColor: `${NAVY}20` }}
          >
            Rafraîchir <RefreshCw className="h-3.5 w-3.5" />
          </button>
        </div>
      </div>

      {/* ── Accès rapides ──────────────────────────────────────────────── */}
      <div>
        <SectionHeader title="Accès rapides" sub="Modules d'administration" />
        <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
          {[
            { label: "Créer un tenant",        href: "admin/tenants",  icon: Building2, color: NAVY  },
            { label: "Gérer les utilisateurs", href: "admin/users",    icon: Users,     color: TEAL  },
            { label: "Sécurité & RBAC",        href: "admin/security", icon: Shield,    color: NAVY2 },
            { label: "Paramètres",             href: "admin/settings", icon: Settings,  color: SLATE },
          ].map((q) => {
            const Icon = q.icon
            return (
              <Link
                key={q.label}
                href={`/${locale}/${q.href}`}
                className="group flex flex-col items-start gap-3 rounded-2xl border bg-white p-4 shadow-sm transition hover:shadow-md hover:-translate-y-0.5"
              >
                <div
                  className="flex h-10 w-10 items-center justify-center rounded-xl ring-1 transition"
                  style={{ background: `${q.color}10`, borderColor: `${q.color}20` }}
                >
                  <Icon className="h-4 w-4" style={{ color: q.color }} />
                </div>
                <div>
                  <p className="text-sm font-semibold text-slate-700 group-hover:text-slate-900 transition">{q.label}</p>
                  <ChevronRight className="mt-0.5 h-3.5 w-3.5 text-slate-300 group-hover:text-slate-400 transition" />
                </div>
              </Link>
            )
          })}
        </div>
      </div>

    </div>
  )
}
