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

export default async function AdminNewArrivalsPage() {
  const section = await prisma.homepageSection.findUnique({ where: { key: "new_arrivals" } });
  const limit = section?.itemLimit ?? 8;

  const products = await prisma.product.findMany({
    where: { active: true },
    include: { category: true },
    orderBy: { createdAt: "desc" },
    take: limit,
  });

  return (
    <div>
      <h1 className="font-[family-name:var(--font-heading)] text-2xl font-bold text-stone-800">New Arrivals</h1>
      <p className="mt-1 text-sm text-stone-500">
        Automatic — the {limit} most recently added active products. Change the count on{" "}
        <Link href="/iv-manage-84x2/marketing/sections" className="text-rose-700 hover:underline">
          Homepage Sections
        </Link>
        .
      </p>

      <MarketingTabs active="/iv-manage-84x2/marketing/new-arrivals" />

      <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">Product</th>
              <th className="p-3">Category</th>
              <th className="p-3">Added</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-rose-100">
            {products.map((p) => (
              <tr key={p.id}>
                <td className="whitespace-nowrap p-3">
                  <Link href={`/iv-manage-84x2/products/${p.id}`} className="font-medium text-rose-700 hover:underline">
                    {p.name}
                  </Link>
                </td>
                <td className="whitespace-nowrap p-3 text-stone-600">{p.category.name}</td>
                <td className="whitespace-nowrap p-3 text-stone-500">{formatDate(p.createdAt)}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </ScrollableTable>
    </div>
  );
}
