import Link from "next/link";
import { notFound } from "next/navigation";
import { db } from "@/lib/db";

export default async function BrandPage({
  params,
}: {
  params: Promise<{ slug: string }>;
}) {
  const { slug } = await params;
  const brand = await db.brand.findUnique({
    where: { slug },
    include: {
      blends: {
        orderBy: { name: "asc" },
        include: {
          _count: { select: { labels: { where: { status: "active" } } } },
        },
      },
    },
  });

  if (!brand) {
    notFound();
  }

  const withLabels = brand.blends.filter((b) => b._count.labels > 0).length;

  return (
    <main className="mx-auto max-w-6xl px-6 py-16">
      <h1 className="font-heading text-4xl font-semibold text-terracotta">
        {brand.name}
      </h1>
      <p className="mt-2 text-charcoal/60">
        {withLabels} of {brand.blends.length} blends have labels
      </p>

      {brand.blends.length === 0 ? (
        <p className="mt-8 text-charcoal/60">No blends yet for this brand.</p>
      ) : (
        <ul className="mt-10 grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
          {brand.blends.map((blend) => (
            <li key={blend.id}>
              <Link
                href={`/brands/${brand.slug}/${blend.slug}`}
                className="block rounded-lg border border-charcoal/10 bg-warm-white p-4 hover:border-terracotta"
              >
                <h2 className="font-heading text-xl font-semibold text-charcoal">
                  {blend.name}
                </h2>
                <p className="mt-1 text-sm text-charcoal/50">
                  {blend._count.labels === 0
                    ? "No labels yet"
                    : `${blend._count.labels} label${blend._count.labels === 1 ? "" : "s"}`}
                </p>
              </Link>
            </li>
          ))}
        </ul>
      )}
    </main>
  );
}
