import Link from "next/link";
import { notFound } from "next/navigation";
import { ArrowLeft, Heart, Mail, Phone, ShoppingBag } from "lucide-react";
import { prisma } from "@/lib/prisma";
import { formatPrice } from "@/lib/money";
import { AdminPageHeader } from "@/components/admin/page-header";
import { OrderStatusBadge } from "@/components/admin/status-badge";
import { AdminStat } from "@/components/admin/stat-card";

const countryNames = new Intl.DisplayNames(["fr"], { type: "region" });

export default async function AdminCustomerDetailPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  const customer = await prisma.user.findUnique({
    where: { id },
    include: {
      addresses: { orderBy: [{ isDefault: "desc" }, { createdAt: "desc" }] },
      orders: { orderBy: { createdAt: "desc" }, include: { _count: { select: { items: true } } } },
      wishlist: { include: { items: true } },
      _count: { select: { reviews: true } },
    },
  });

  if (!customer || customer.role === "SUPERADMIN") notFound();

  const activeOrders = customer.orders.filter((order) => order.status !== "CANCELLED");
  const spent = activeOrders.reduce((sum, order) => sum + order.total, 0);
  const average = activeOrders.length ? Math.round(spent / activeOrders.length) : 0;

  return (
    <div className="space-y-5">
      <Link href="/admin/customers" className="inline-flex items-center gap-2 text-[12px] uppercase tracking-[0.14em] text-pebble hover:text-charcoal">
        <ArrowLeft className="h-3.5 w-3.5" />
        Tous les clients
      </Link>

      <AdminPageHeader
        eyebrow={`Client depuis ${new Intl.DateTimeFormat("fr-FR", { month: "long", year: "numeric" }).format(customer.createdAt)}`}
        title={customer.name}
        description={customer.email}
        actions={
          customer.role === "ADMIN" ? (
            <span className="border border-gold/30 bg-gold/5 px-2 py-1 text-[12px] uppercase tracking-[0.12em] text-gold-ink">
              Administrateur
            </span>
          ) : undefined
        }
      />

      <div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
        <AdminStat label="Commandes" value={String(customer.orders.length)} hint={`${activeOrders.length} active(s)`} icon={<ShoppingBag className="h-4 w-4" strokeWidth={1.4} />} />
        <AdminStat label="Total dépensé" value={formatPrice(spent)} hint="Hors commandes annulées" tone="gold" icon={<ShoppingBag className="h-4 w-4" strokeWidth={1.4} />} />
        <AdminStat label="Panier moyen" value={formatPrice(average)} icon={<ShoppingBag className="h-4 w-4" strokeWidth={1.4} />} tone="olive" />
        <AdminStat label="Favoris" value={String(customer.wishlist?.items.length ?? 0)} hint={`${customer._count.reviews} avis déposé(s)`} icon={<Heart className="h-4 w-4" strokeWidth={1.4} />} />
      </div>

      <div className="grid gap-4 xl:grid-cols-[1fr_340px]">
        <section className="border border-line bg-cream">
          <div className="border-b border-line px-5 py-4">
            <h2 className="font-serif text-xl font-light">Historique des commandes</h2>
          </div>
          <div className="divide-y divide-border">
            {customer.orders.map((order) => (
              <Link key={order.id} href={`/admin/orders/${order.id}`} className="flex flex-wrap items-center justify-between gap-3 px-5 py-3.5 transition-colors hover:bg-cream/40">
                <div>
                  <p className="font-medium tracking-wide text-charcoal">{order.reference}</p>
                  <p className="mt-0.5 text-[12px] text-pebble">
                    {new Intl.DateTimeFormat("fr-FR", { day: "2-digit", month: "short", year: "numeric" }).format(order.createdAt)} · {order._count.items} article(s)
                  </p>
                </div>
                <div className="flex items-center gap-3">
                  <OrderStatusBadge status={order.status} />
                  <p className="w-24 text-right text-[14px] tabular-nums text-charcoal">{formatPrice(order.total)}</p>
                </div>
              </Link>
            ))}
            {customer.orders.length === 0 && (
              <p className="px-5 py-12 text-center text-[14px] text-pebble">Aucune commande enregistrée.</p>
            )}
          </div>
        </section>

        <aside className="space-y-4">
          <section className="border border-line bg-cream p-5">
            <h2 className="font-serif text-lg font-light">Coordonnées</h2>
            <div className="mt-3 space-y-2.5 text-[14px] text-walnut">
              <p className="flex items-center gap-2"><Mail className="h-3.5 w-3.5 text-pebble" />{customer.email}</p>
              <p className="flex items-center gap-2"><Phone className="h-3.5 w-3.5 text-pebble" />{customer.phone || "Non renseigné"}</p>
            </div>
          </section>

          <section className="border border-line bg-cream p-5">
            <h2 className="font-serif text-lg font-light">Adresses</h2>
            <div className="mt-3 space-y-3">
              {customer.addresses.map((address) => (
                <div key={address.id} className="border border-line p-3 text-[13px] leading-relaxed text-walnut">
                  <div className="mb-1 flex items-center justify-between">
                    <span className="text-[12px] uppercase tracking-[0.12em] text-pebble">{address.label}</span>
                    {address.isDefault && <span className="text-[12px] uppercase tracking-[0.1em] text-gold-ink">Par défaut</span>}
                  </div>
                  <p className="text-charcoal/80">{address.fullName}</p>
                  <p>{address.addressLine1}</p>
                  {address.addressLine2 && <p>{address.addressLine2}</p>}
                  <p>{address.postalCode ? `${address.postalCode} ` : ""}{address.city}, {countryNames.of(address.country) ?? address.country}</p>
                  <p className="mt-1">{address.phone}</p>
                </div>
              ))}
              {customer.addresses.length === 0 && (
                <p className="text-[13px] text-pebble">Aucune adresse enregistrée.</p>
              )}
            </div>
          </section>

          <section className="border border-line bg-cream p-5">
            <h2 className="font-serif text-lg font-light">Favoris</h2>
            <p className="mt-2 flex items-center gap-2 text-[13px] text-pebble">
              <Heart className="h-3.5 w-3.5 text-gold-ink" />
              {customer.wishlist?.items.length ?? 0} pièce(s) enregistrée(s)
            </p>
          </section>
        </aside>
      </div>
    </div>
  );
}
