import Link from "next/link";
import { prisma } from "@/lib/prisma";
import { formatPaise, formatDate } from "@/lib/format";
import CustomersTabs from "@/components/admin/CustomersTabs";
import ScrollableTable from "@/components/admin/ScrollableTable";

export default async function AdminCustomerOrderHistoryPage() {
  const orders = await prisma.order.findMany({
    select: { email: true, customerName: true, total: true, status: true, createdAt: true },
    orderBy: { createdAt: "desc" },
  });

  type Row = {
    email: string;
    customerName: string;
    totalOrders: number;
    paidOrders: number;
    totalSpent: number;
    lastOrder: Date;
  };

  const byEmail = new Map<string, Row>();
  for (const o of orders) {
    const row = byEmail.get(o.email) ?? {
      email: o.email,
      customerName: o.customerName,
      totalOrders: 0,
      paidOrders: 0,
      totalSpent: 0,
      lastOrder: o.createdAt,
    };
    row.totalOrders += 1;
    if (o.status === "paid") {
      row.paidOrders += 1;
      row.totalSpent += o.total;
    }
    if (o.createdAt > row.lastOrder) row.lastOrder = o.createdAt;
    byEmail.set(o.email, row);
  }
  const rows = [...byEmail.values()].sort((a, b) => b.totalSpent - a.totalSpent);

  return (
    <div>
      <h1 className="font-[family-name:var(--font-heading)] text-2xl font-bold text-stone-800">Customer Order History</h1>
      <p className="mt-1 text-sm text-stone-500">
        Every customer who has placed at least one order (registered or guest checkout), ranked by total spent.
      </p>

      <CustomersTabs active="/iv-manage-84x2/customers/order-history" />

      {rows.length === 0 ? (
        <p className="rounded-lg border border-rose-100 bg-white p-4 text-sm text-stone-500">No orders yet.</p>
      ) : (
        <ScrollableTable>
          <table className="w-full min-w-[800px] text-sm">
            <thead className="sticky top-0 z-10 bg-rose-50 text-left text-xs uppercase text-stone-500">
              <tr>
                <th className="p-3">Customer</th>
                <th className="p-3">Orders</th>
                <th className="p-3">Paid orders</th>
                <th className="p-3">Total spent</th>
                <th className="p-3">Avg. order value</th>
                <th className="p-3">Last order</th>
                <th className="p-3"></th>
              </tr>
            </thead>
            <tbody className="divide-y divide-rose-100">
              {rows.map((r) => (
                <tr key={r.email}>
                  <td className="whitespace-nowrap p-3">
                    <p className="font-medium text-stone-800">{r.customerName}</p>
                    <p className="text-xs text-stone-500">{r.email}</p>
                  </td>
                  <td className="whitespace-nowrap p-3 text-stone-600">{r.totalOrders}</td>
                  <td className="whitespace-nowrap p-3 text-stone-600">{r.paidOrders}</td>
                  <td className="whitespace-nowrap p-3 text-stone-600">{formatPaise(r.totalSpent)}</td>
                  <td className="whitespace-nowrap p-3 text-stone-600">
                    {r.paidOrders > 0 ? formatPaise(Math.round(r.totalSpent / r.paidOrders)) : "—"}
                  </td>
                  <td className="whitespace-nowrap p-3 text-stone-500">{formatDate(r.lastOrder)}</td>
                  <td className="whitespace-nowrap p-3">
                    <Link href={`/iv-manage-84x2/orders?email=${encodeURIComponent(r.email)}`} className="text-xs font-medium text-rose-700 hover:underline">
                      View orders →
                    </Link>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </ScrollableTable>
      )}
    </div>
  );
}
