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

export default async function AdminBestSellersPage() {
  const items = await prisma.orderItem.findMany({
    where: { order: { status: "paid" } },
    include: { product: { include: { category: true } } },
  });

  type Row = { productId: string; name: string; category: string; unitsSold: number; revenue: number };
  const byProduct = new Map<string, Row>();
  for (const item of items) {
    const row = byProduct.get(item.productId) ?? {
      productId: item.productId,
      name: item.product.name,
      category: item.product.category.name,
      unitsSold: 0,
      revenue: 0,
    };
    row.unitsSold += item.quantity;
    row.revenue += item.lineTotal;
    byProduct.set(item.productId, row);
  }
  const rows = [...byProduct.values()].sort((a, b) => b.unitsSold - a.unitsSold);

  return (
    <div>
      <h1 className="font-[family-name:var(--font-heading)] text-2xl font-bold text-stone-800">Best Sellers</h1>
      <p className="mt-1 text-sm text-stone-500">
        Computed automatically from paid orders — units actually sold, not a manually curated list. This is what feeds the
        homepage &ldquo;Best sellers&rdquo; section when it&apos;s turned on.
      </p>

      <MarketingTabs active="/iv-manage-84x2/marketing/best-sellers" />

      {rows.length === 0 ? (
        <p className="rounded-lg border border-rose-100 bg-white p-4 text-sm text-stone-500">
          No paid orders yet — nothing to rank. The homepage section will simply show nothing until there&apos;s real sales data.
        </p>
      ) : (
        <ScrollableTable>
          <table className="w-full min-w-[700px] 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">#</th>
                <th className="p-3">Product</th>
                <th className="p-3">Category</th>
                <th className="p-3">Units sold</th>
                <th className="p-3">Revenue</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-rose-100">
              {rows.map((r, i) => (
                <tr key={r.productId}>
                  <td className="whitespace-nowrap p-3 text-stone-500">{i + 1}</td>
                  <td className="whitespace-nowrap p-3">
                    <Link href={`/iv-manage-84x2/products/${r.productId}`} className="font-medium text-rose-700 hover:underline">
                      {r.name}
                    </Link>
                  </td>
                  <td className="whitespace-nowrap p-3 text-stone-600">{r.category}</td>
                  <td className="whitespace-nowrap p-3 text-stone-600">{r.unitsSold}</td>
                  <td className="whitespace-nowrap p-3 text-stone-600">{formatPaise(r.revenue)}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </ScrollableTable>
      )}
    </div>
  );
}
