import { db } from "@/lib/db"
import Link from "next/link"
import { Badge } from "@/components/ui/badge"
import { formatPrice } from "@/lib/utils"
import {
  Package,
  Sparkles,
  ShoppingCart,
  Mail,
  Users,
  Layers,
  ArrowRight,
} from "lucide-react"

export const metadata = { title: "Admin — Tableau de bord" }

const ORDER_STATUS_LABEL: Record<string, string> = {
  PENDING: "En attente",
  PAID: "Payée",
  SHIPPED: "Expédiée",
  DELIVERED: "Livrée",
  CANCELLED: "Annulée",
}

export default async function AdminDashboardPage() {
  const [
    productCount,
    activeProductCount,
    dropCount,
    liveDropCount,
    orderCount,
    revenueAgg,
    newsletterCount,
    userCount,
    collaboratorCount,
    categoryCount,
    recentOrders,
  ] = await Promise.all([
    db.product.count(),
    db.product.count({ where: { active: true } }),
    db.drop.count(),
    db.drop.count({ where: { status: "LIVE" } }),
    db.order.count(),
    db.order.aggregate({
      _sum: { total: true },
      where: { status: { in: ["PAID", "SHIPPED", "DELIVERED"] } },
    }),
    db.newsletter.count(),
    db.user.count(),
    db.collaborator.count(),
    db.category.count(),
    db.order.findMany({
      include: { user: true, items: true },
      orderBy: { createdAt: "desc" },
      take: 5,
    }),
  ])

  const kpis = [
    {
      label: "Chiffre d'affaires",
      value: formatPrice(revenueAgg._sum.total ?? 0),
      icon: ShoppingCart,
      href: "/admin/orders",
    },
    {
      label: "Commandes",
      value: orderCount.toString(),
      icon: ShoppingCart,
      href: "/admin/orders",
    },
    {
      label: "Produits actifs",
      value: `${activeProductCount} / ${productCount}`,
      icon: Package,
      href: "/admin/products",
    },
    {
      label: "Drops live",
      value: `${liveDropCount} / ${dropCount}`,
      icon: Sparkles,
      href: "/admin/drops",
    },
    {
      label: "Abonnés newsletter",
      value: newsletterCount.toString(),
      icon: Mail,
      href: "/admin/newsletter",
    },
    {
      label: "Comptes utilisateurs",
      value: userCount.toString(),
      icon: Users,
      href: "/admin/users",
    },
    {
      label: "Collaborateurs",
      value: collaboratorCount.toString(),
      icon: Users,
      href: "/admin/collaborators",
    },
    {
      label: "Catégories",
      value: categoryCount.toString(),
      icon: Layers,
      href: "/admin/categories",
    },
  ]

  const sections = [
    { href: "/admin/products", label: "Produits", desc: "Catalogue, prix, stock, éditions limitées" },
    { href: "/admin/drops", label: "Drops", desc: "Capsules, dates, collaborateurs, vidéos" },
    { href: "/admin/collaborators", label: "Collaborateurs", desc: "Stylistes et artistes des drops" },
    { href: "/admin/categories", label: "Catégories", desc: "Hoodies, vestes, accessoires…" },
    { href: "/admin/orders", label: "Commandes", desc: "Suivi et statuts des commandes" },
    { href: "/admin/newsletter", label: "Newsletter", desc: "Abonnés collectés sur le site" },
    { href: "/admin/users", label: "Utilisateurs", desc: "Comptes clients et administrateurs" },
  ]

  return (
    <div>
      <h1 className="text-2xl font-heading font-bold uppercase tracking-tight text-[var(--text)] mb-8">
        Tableau de bord
      </h1>

      {/* KPIs */}
      <div className="grid grid-cols-2 lg:grid-cols-3 gap-4 mb-12">
        {kpis.map((kpi) => (
          <Link
            key={kpi.label}
            href={kpi.href}
            className="border border-[var(--border)] bg-[var(--surface)] p-5 hover:border-[var(--border-subtle)] transition-colors"
          >
            <div className="flex items-center justify-between mb-3">
              <kpi.icon size={16} className="text-[var(--accent)]" />
            </div>
            <p className="text-2xl font-heading font-bold text-[var(--text)]">{kpi.value}</p>
            <p className="font-mono text-xs uppercase tracking-widest text-[var(--text-muted)] mt-1">
              {kpi.label}
            </p>
          </Link>
        ))}
      </div>

      {/* Navigation par section */}
      <h2 className="font-mono text-xs uppercase tracking-widest text-[var(--text-muted)] mb-4">
        Configuration
      </h2>
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 mb-12">
        {sections.map((s) => (
          <Link
            key={s.href}
            href={s.href}
            className="group flex items-start justify-between gap-3 border border-[var(--border)] bg-[var(--surface)] p-5 hover:border-[var(--border-subtle)] transition-colors"
          >
            <div>
              <p className="font-heading font-semibold text-[var(--text)]">{s.label}</p>
              <p className="text-sm text-[var(--text-secondary)] mt-1">{s.desc}</p>
            </div>
            <ArrowRight
              size={16}
              className="shrink-0 mt-1 text-[var(--text-muted)] group-hover:text-[var(--accent)] group-hover:translate-x-0.5 transition-all"
            />
          </Link>
        ))}
      </div>

      {/* Commandes récentes */}
      <div className="flex items-center justify-between mb-4">
        <h2 className="font-mono text-xs uppercase tracking-widest text-[var(--text-muted)]">
          Commandes récentes
        </h2>
        <Link
          href="/admin/orders"
          className="font-mono text-xs uppercase tracking-widest text-[var(--text-secondary)] hover:text-[var(--text)] transition-colors"
        >
          Tout voir →
        </Link>
      </div>
      <div className="border border-[var(--border)] bg-[var(--surface)]">
        <table className="w-full text-sm">
          <thead>
            <tr className="border-b border-[var(--border)]">
              {["#", "Client", "Articles", "Total", "Statut", "Date"].map((h) => (
                <th
                  key={h}
                  className="text-left px-4 py-3 font-mono text-xs uppercase tracking-widest text-[var(--text-muted)]"
                >
                  {h}
                </th>
              ))}
            </tr>
          </thead>
          <tbody className="divide-y divide-[var(--border)]">
            {recentOrders.map((order) => (
              <tr key={order.id} className="hover:bg-[var(--surface-raised)] transition-colors">
                <td className="px-4 py-4">
                  <Link
                    href={`/admin/orders/${order.id}`}
                    className="font-mono text-xs text-[var(--text-muted)] hover:text-[var(--accent)]"
                  >
                    #{order.id.slice(-8).toUpperCase()}
                  </Link>
                </td>
                <td className="px-4 py-4 text-[var(--text)]">{order.user.email}</td>
                <td className="px-4 py-4 font-mono text-[var(--text-secondary)]">{order.items.length}</td>
                <td className="px-4 py-4 font-mono font-bold text-[var(--text)]">
                  {formatPrice(order.total)}
                </td>
                <td className="px-4 py-4">
                  <Badge variant="outline">{ORDER_STATUS_LABEL[order.status]}</Badge>
                </td>
                <td className="px-4 py-4 text-[var(--text-secondary)]">
                  {new Date(order.createdAt).toLocaleDateString("fr-BE")}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
        {recentOrders.length === 0 && (
          <div className="py-16 text-center text-[var(--text-muted)] flex flex-col items-center gap-2">
            <Layers size={20} className="text-[var(--text-muted)]" />
            Aucune commande pour le moment.
          </div>
        )}
      </div>
    </div>
  )
}
