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

const LOW_STOCK_THRESHOLD = 10;

export default async function AdminLowStockPage() {
  const [lowProducts, lowVariants] = await Promise.all([
    prisma.product.findMany({
      where: { stock: { lte: LOW_STOCK_THRESHOLD, not: null } },
      include: { category: true },
      orderBy: { stock: "asc" },
    }),
    prisma.productVariant.findMany({
      where: { stock: { lte: LOW_STOCK_THRESHOLD } },
      include: { product: { include: { category: true } } },
      orderBy: { stock: "asc" },
    }),
  ]);

  type Row = { id: string; name: string; category: string; stock: number; productId: string };
  const rows: Row[] = [
    ...lowProducts.map((p) => ({ id: p.id, name: p.name, category: p.category.name, stock: p.stock ?? 0, productId: p.id })),
    ...lowVariants.map((v) => ({
      id: v.id,
      name: `${v.product.name} (${v.name})`,
      category: v.product.category.name,
      stock: v.stock,
      productId: v.productId,
    })),
  ].sort((a, b) => a.stock - b.stock);

  return (
    <div>
      <h1 className="font-[family-name:var(--font-heading)] text-2xl font-bold text-stone-800">Low Stock</h1>
      <p className="mt-1 text-sm text-stone-500">Products and variants at or below {LOW_STOCK_THRESHOLD} units.</p>

      <InventoryTabs active="/iv-manage-84x2/inventory/low-stock" />

      {rows.length === 0 ? (
        <p className="rounded-lg border border-rose-100 bg-white p-4 text-sm text-stone-500">
          Nothing is running low right now.
        </p>
      ) : (
        <ScrollableTable>
          <table className="w-full min-w-[600px] 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">Name</th>
                <th className="p-3">Category</th>
                <th className="p-3">Stock</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-rose-100">
              {rows.map((r) => (
                <tr key={r.id}>
                  <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">
                    <span
                      className={`rounded-full px-2 py-0.5 text-xs font-medium ${
                        r.stock === 0 ? "bg-red-100 text-red-800" : "bg-amber-100 text-amber-800"
                      }`}
                    >
                      {r.stock} left
                    </span>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </ScrollableTable>
      )}
    </div>
  );
}
