import Link from "next/link";
import type { Metadata } from "next";
import { prisma } from "@/lib/prisma";
import ProductCard from "@/components/ProductCard";

export async function generateMetadata({
  searchParams,
}: {
  searchParams: Promise<{ category?: string }>;
}): Promise<Metadata> {
  const { category } = await searchParams;
  if (category) {
    const cat = await prisma.category.findUnique({ where: { slug: category } });
    if (cat) {
      return {
        title: cat.metaTitle || `${cat.name} — Iniyaval Return Gifts`,
        description: cat.metaDescription || undefined,
      };
    }
  }
  const page = await prisma.pageSeo.findUnique({ where: { path: "/shop" } });
  return { title: page?.title || undefined, description: page?.description || undefined };
}

export default async function ShopPage({
  searchParams,
}: {
  searchParams: Promise<{ category?: string; collection?: string; maxPrice?: string }>;
}) {
  const { category, collection, maxPrice } = await searchParams;
  const maxPricePaise = maxPrice ? Math.round(Number(maxPrice) * 100) : undefined;

  const [categories, products, activeCollection, activeCategory] = await Promise.all([
    prisma.category.findMany({ where: { products: { some: { active: true } } }, orderBy: { name: "asc" } }),
    prisma.product.findMany({
      where: {
        active: true,
        ...(category ? { category: { slug: category } } : {}),
        ...(collection ? { collections: { some: { slug: collection } } } : {}),
        ...(maxPricePaise
          ? { OR: [{ basePrice: { lte: maxPricePaise } }, { salePrice: { lte: maxPricePaise } }] }
          : {}),
      },
      include: { category: true, variants: true },
      orderBy: { createdAt: "desc" },
    }),
    collection ? prisma.collection.findUnique({ where: { slug: collection } }) : Promise.resolve(null),
    // Looked up independently of the pills list above, which only includes categories with active
    // products — a category can be validly selected via a nav link while having zero of its own yet.
    category ? prisma.category.findUnique({ where: { slug: category } }) : Promise.resolve(null),
  ]);

  const heading = activeCollection
    ? activeCollection.name
    : activeCategory
      ? activeCategory.name
      : maxPricePaise
        ? `Return Gifts Under ₹${maxPrice}`
        : "All return gifts";

  return (
    <div className="mx-auto max-w-7xl px-4 py-10 sm:px-6">
      <h1 className="font-[family-name:var(--font-heading)] text-2xl font-bold text-stone-800">{heading}</h1>

      {!collection && (
        <div className="mt-4 flex flex-wrap gap-2">
          <Link
            href="/shop"
            className={`rounded-full border px-3 py-1.5 text-sm ${
              !category ? "border-rose-700 bg-rose-700 text-white" : "border-rose-200 text-stone-600 hover:bg-rose-50"
            }`}
          >
            All
          </Link>
          {categories.map((c) => (
            <Link
              key={c.id}
              href={`/shop?category=${c.slug}`}
              className={`rounded-full border px-3 py-1.5 text-sm ${
                category === c.slug
                  ? "border-rose-700 bg-rose-700 text-white"
                  : "border-rose-200 text-stone-600 hover:bg-rose-50"
              }`}
            >
              {c.name}
            </Link>
          ))}
        </div>
      )}

      {products.length === 0 ? (
        <p className="mt-10 text-sm text-stone-500">No products found here yet.</p>
      ) : (
        <div className="mt-8 grid grid-cols-2 gap-4 sm:grid-cols-3 lg:grid-cols-4">
          {products.map((p) => (
            <ProductCard key={p.id} product={p} />
          ))}
        </div>
      )}
    </div>
  );
}
