import Link from "next/link";
import { Search } from "lucide-react";
import type { Prisma } from "@prisma/client";
import { prisma } from "@/lib/prisma";
import { formatPrice } from "@/lib/money";
import { parsePage } from "@/lib/utils";
import { AdminPageHeader } from "@/components/admin/page-header";
import { Pagination } from "@/components/store/pagination";
import { Input } from "@/components/ui/input";

const PAGE_SIZE = 20;

export default async function AdminCustomersPage({
  searchParams,
}: {
  searchParams: Promise<Record<string, string | string[] | undefined>>;
}) {
  const params = await searchParams;
  const q = typeof params.q === "string" ? params.q.trim() : "";
  const role = typeof params.role === "string" ? params.role : "";
  const page = parsePage(params.page);
  const roleFilter = role === "ADMIN" || role === "CUSTOMER" ? role : undefined;

  const where: Prisma.UserWhereInput = {
    // Never expose the owner/superadmin account in the back-office listings.
    role: roleFilter ?? { not: "SUPERADMIN" },
    ...(q
      ? {
          OR: [
            { name: { contains: q } },
            { email: { contains: q } },
            { phone: { contains: q } },
          ],
        }
      : {}),
  };

  const [customers, total, customerCount, adminCount] = await Promise.all([
    prisma.user.findMany({
      where,
      include: {
        addresses: { where: { isDefault: true }, take: 1 },
        orders: { where: { status: { not: "CANCELLED" } }, select: { total: true, createdAt: true } },
        _count: { select: { orders: true, reviews: true } },
      },
      orderBy: { createdAt: "desc" },
      skip: (page - 1) * PAGE_SIZE,
      take: PAGE_SIZE,
    }),
    prisma.user.count({ where }),
    prisma.user.count({ where: { role: "CUSTOMER" } }),
    prisma.user.count({ where: { role: "ADMIN" } }),
  ]);

  const totalPages = Math.max(1, Math.ceil(total / PAGE_SIZE));

  return (
    <div className="space-y-5">
      <AdminPageHeader
        eyebrow="Ventes"
        title="Clients"
        description={`${customerCount} client(s) · ${adminCount} administrateur(s)`}
      />

      <form className="grid gap-2 border border-line bg-cream p-3 md:grid-cols-[1fr_170px_auto]">
        <div className="relative">
          <Search className="pointer-events-none absolute left-3 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-pebble" />
          <Input
            name="q"
            defaultValue={q}
            placeholder="Nom, e-mail ou téléphone…"
            className="h-9 rounded-none border-line bg-transparent pl-8 text-[14px]"
          />
        </div>
        <select
          name="role"
          defaultValue={role}
          className="h-9 w-full border border-line bg-cream px-2.5 text-[14px] focus:border-charcoal focus:outline-none"
        >
          <option value="">Tous les rôles</option>
          <option value="CUSTOMER">Clients</option>
          <option value="ADMIN">Administrateurs</option>
        </select>
        <div className="flex gap-2">
          <button type="submit" className="h-9 bg-charcoal px-4 text-[12px] uppercase tracking-[0.14em] text-ivory hover:opacity-90">
            Filtrer
          </button>
          <Link href="/admin/customers" className="flex h-9 items-center border border-line px-3 text-[12px] uppercase tracking-[0.12em] text-pebble hover:border-charcoal/40">
            Effacer
          </Link>
        </div>
      </form>

      <div className="overflow-x-auto border border-line bg-cream">
        <table className="w-full min-w-[820px] text-left text-[14px]">
          <thead>
            <tr className="border-b border-line text-[12px] uppercase tracking-[0.14em] text-pebble">
              <th className="px-4 py-3 font-medium">Client</th>
              <th className="px-3 py-3 font-medium">Ville</th>
              <th className="px-3 py-3 font-medium">Commandes</th>
              <th className="px-3 py-3 font-medium">Total dépensé</th>
              <th className="px-3 py-3 font-medium">Dernière commande</th>
              <th className="px-3 py-3 font-medium">Inscrit le</th>
              <th className="px-4 py-3 text-right font-medium">Accès</th>
            </tr>
          </thead>
          <tbody>
            {customers.map((customer) => {
              const spent = customer.orders.reduce((sum, order) => sum + order.total, 0);
              const lastOrder = customer.orders.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime())[0];
              return (
                <tr key={customer.id} className="border-b border-line/70 last:border-0 hover:bg-cream/30">
                  <td className="px-4 py-3.5">
                    <div className="flex items-center gap-3">
                      <div className="flex h-8 w-8 items-center justify-center rounded-full border border-line bg-cream font-serif text-[14px] text-walnut">
                        {customer.name.charAt(0).toUpperCase()}
                      </div>
                      <div>
                        <Link href={`/admin/customers/${customer.id}`} className="font-medium text-charcoal hover:underline">
                          {customer.name}
                        </Link>
                        <p className="mt-0.5 text-[12px] text-pebble">{customer.email}</p>
                      </div>
                      {customer.role === "ADMIN" && (
                        <span className="border border-gold/30 bg-gold/5 px-1.5 py-0.5 text-[12px] uppercase tracking-[0.1em] text-gold-ink">
                          Admin
                        </span>
                      )}
                    </div>
                  </td>
                  <td className="px-3 py-3.5 text-pebble">{customer.addresses[0]?.city ?? "—"}</td>
                  <td className="px-3 py-3.5 text-walnut">{customer._count.orders}</td>
                  <td className="px-3 py-3.5 tabular-nums text-charcoal">{formatPrice(spent)}</td>
                  <td className="px-3 py-3.5 text-pebble">
                    {lastOrder ? new Intl.DateTimeFormat("fr-FR", { day: "2-digit", month: "short", year: "numeric" }).format(lastOrder.createdAt) : "—"}
                  </td>
                  <td className="px-3 py-3.5 text-pebble">
                    {new Intl.DateTimeFormat("fr-FR", { day: "2-digit", month: "short", year: "numeric" }).format(customer.createdAt)}
                  </td>
                  <td className="px-4 py-3.5 text-right">
                    <Link href={`/admin/customers/${customer.id}`} className="text-[12px] uppercase tracking-[0.12em] text-pebble hover:text-charcoal">
                      Consulter
                    </Link>
                  </td>
                </tr>
              );
            })}
            {customers.length === 0 && (
              <tr>
                <td colSpan={7} className="px-4 py-16 text-center text-[14px] text-pebble">
                  Aucun client ne correspond à ces filtres.
                </td>
              </tr>
            )}
          </tbody>
        </table>
      </div>

      <Pagination
        page={page}
        totalPages={totalPages}
        basePath="/admin/customers"
        params={{ q: q || undefined, role: role || undefined }}
        labels={{ previous: "Page précédente", next: "Page suivante" }}
      />
    </div>
  );
}
