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

export default async function SearchPage({
  searchParams,
}: {
  searchParams: Promise<{ q?: string }>;
}) {
  const { q } = await searchParams;
  const query = (q ?? "").trim();

  const products = query
    ? await prisma.product.findMany({
        where: {
          active: true,
          OR: [
            { name: { contains: query } },
            { description: { contains: query } },
          ],
        },
        include: { category: true, variants: true },
        orderBy: { createdAt: "desc" },
      })
    : [];

  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">
        {query ? `Search results for "${query}"` : "Search"}
      </h1>

      {!query ? (
        <p className="mt-4 text-sm text-stone-500">Type something in the search bar above to find products.</p>
      ) : products.length === 0 ? (
        <p className="mt-4 text-sm text-stone-500">
          No products matched &ldquo;{query}&rdquo;. Try a different word, or{" "}
          <Link href="/shop" className="text-rose-700 hover:underline">browse all products</Link>.
        </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>
  );
}
