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

const PAGE_SIZE = 20;

const statusLabels: Record<string, string> = {
  "": "Toutes",
  PENDING: "En attente",
  CONFIRMED: "Confirmées",
  PROCESSING: "En préparation",
  SHIPPED: "Expédiées",
  DELIVERED: "Livrées",
  CANCELLED: "Annulées",
};

const selectClass =
  "h-9 w-full border border-line bg-cream px-2.5 text-[14px] text-charcoal focus:border-charcoal focus:outline-none";

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

  const where: Prisma.OrderWhereInput = {
    ...(q
      ? {
          OR: [
            { reference: { contains: q } },
            { customerName: { contains: q } },
            { email: { contains: q } },
            { phone: { contains: q } },
          ],
        }
      : {}),
    ...(status ? { status } : {}),
    ...(payment ? { paymentMethod: payment } : {}),
  };

  const [orders, total, statusCounts, revenue] = await Promise.all([
    prisma.order.findMany({
      where,
      include: { _count: { select: { items: true } } },
      orderBy: { createdAt: "desc" },
      skip: (page - 1) * PAGE_SIZE,
      take: PAGE_SIZE,
    }),
    prisma.order.count({ where }),
    prisma.order.groupBy({ by: ["status"], _count: { _all: true } }),
    prisma.order.aggregate({
      where: { status: { not: "CANCELLED" } },
      _sum: { total: true },
    }),
  ]);

  const allCount = statusCounts.reduce((sum, entry) => sum + entry._count._all, 0);
  const totalPages = Math.max(1, Math.ceil(total / PAGE_SIZE));

  const buildHref = (nextStatus: string) => {
    const query = new URLSearchParams();
    if (q) query.set("q", q);
    if (payment) query.set("payment", payment);
    if (nextStatus) query.set("status", nextStatus);
    const qs = query.toString();
    return `/admin/orders${qs ? `?${qs}` : ""}`;
  };

  return (
    <div className="space-y-5">
      <AdminPageHeader
        eyebrow="Ventes"
        title="Commandes"
        description={`${allCount} commande(s) enregistrée(s) · ${formatPrice(
          revenue._sum.total ?? 0,
        )} de chiffre d'affaires hors annulations`}
      />

      <div className="flex flex-wrap gap-x-5 gap-y-2 border-b border-line pb-3">
        {Object.entries(statusLabels).map(([value, label]) => {
          const count = value ? statusCounts.find((entry) => entry.status === value)?._count._all ?? 0 : allCount;
          const active = status === value;
          return (
            <Link
              key={value || "all"}
              href={buildHref(value)}
              className={
                active
                  ? "text-[13px] uppercase tracking-[0.12em] text-charcoal"
                  : "text-[13px] uppercase tracking-[0.12em] text-walnut hover:text-charcoal"
              }
            >
              {label}
              <span className={`ml-1.5 ${active ? "text-gold-ink" : "text-walnut"}`}>{count}</span>
            </Link>
          );
        })}
      </div>

      <form className="grid gap-2 border border-line bg-cream p-3 md:grid-cols-[1fr_170px_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="Référence, client, e-mail ou téléphone…"
            className="h-9 rounded-none border-line bg-transparent pl-8 text-[14px]"
          />
        </div>
        <select name="status" defaultValue={status} className={selectClass}>
          {Object.entries(statusLabels).map(([value, label]) => (
            <option key={value || "all"} value={value}>{label}</option>
          ))}
        </select>
        <select name="payment" defaultValue={payment} className={selectClass}>
          <option value="">Tous paiements</option>
          <option value="COD">Paiement à la livraison</option>
          <option value="BANK_TRANSFER">Virement bancaire</option>
          <option value="ONLINE">Paiement en ligne</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/orders" 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-[900px] 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">Référence</th>
              <th className="px-3 py-3 font-medium">Date</th>
              <th className="px-3 py-3 font-medium">Client</th>
              <th className="px-3 py-3 font-medium">Livraison</th>
              <th className="px-3 py-3 font-medium">Articles</th>
              <th className="px-3 py-3 font-medium">Paiement</th>
              <th className="px-3 py-3 font-medium">Statut</th>
              <th className="px-4 py-3 text-right font-medium">Total</th>
            </tr>
          </thead>
          <tbody>
            {orders.map((order) => (
              <tr key={order.id} className="border-b border-line/70 last:border-0 hover:bg-cream/30">
                <td className="px-4 py-3.5">
                  <Link href={`/admin/orders/${order.id}`} className="font-medium tracking-wide text-charcoal hover:underline">
                    {order.reference}
                  </Link>
                </td>
                <td className="px-3 py-3.5 text-pebble">
                  {new Intl.DateTimeFormat("fr-FR", { day: "2-digit", month: "short", year: "numeric" }).format(order.createdAt)}
                </td>
                <td className="px-3 py-3.5">
                  <p className="text-charcoal/80">{order.customerName}</p>
                  <p className="mt-0.5 text-[12px] text-pebble">{order.email}</p>
                </td>
                <td className="px-3 py-3.5 text-pebble">{order.city}<span className="text-pebble"> · {order.country}</span></td>
                <td className="px-3 py-3.5 text-pebble">{order._count.items}</td>
                <td className="px-3 py-3.5">
                  <p className="text-[12px] text-pebble">
                    {order.paymentMethod === "COD" ? "À la livraison" : order.paymentMethod === "BANK_TRANSFER" ? "Virement" : "En ligne"}
                  </p>
                  <div className="mt-1"><PaymentStatusBadge status={order.paymentStatus} /></div>
                </td>
                <td className="px-3 py-3.5"><OrderStatusBadge status={order.status} /></td>
                <td className="px-4 py-3.5 text-right tabular-nums text-charcoal">{formatPrice(order.total)}</td>
              </tr>
            ))}
            {orders.length === 0 && (
              <tr>
                <td colSpan={8} className="px-4 py-16 text-center text-[14px] text-pebble">
                  Aucune commande ne correspond à ces filtres.
                </td>
              </tr>
            )}
          </tbody>
        </table>
      </div>

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