import { prisma } from "@/lib/prisma";
import ProductCard from "@/components/shop/ProductCard";
import ShopFilters from "@/components/shop/ShopFilters";
import { Metadata } from "next";

export const metadata: Metadata = {
  title: "Shop – Pet Products",
  description: "Browse hundreds of premium pet products for dogs, cats, birds, fish, and more.",
};

interface ShopPageProps {
  searchParams: {
    pet?: string;
    category?: string;
    q?: string;
    sort?: string;
  };
}

export default async function ShopPage({ searchParams }: ShopPageProps) {
  const { pet, category, q, sort } = searchParams;

  const where: {
    active: boolean;
    petType?: { in: string[] };
    category?: string;
    OR?: Array<{ name?: { contains: string }; description?: { contains: string } }>;
  } = { active: true };

  if (pet && pet !== "all") {
    where.petType = { in: [pet, "all"] };
  }
  if (category) {
    where.category = category;
  }
  if (q) {
    where.OR = [
      { name: { contains: q } },
      { description: { contains: q } },
    ];
  }

  let orderBy: Record<string, string> = { createdAt: "desc" };
  if (sort === "price-asc") orderBy = { price: "asc" };
  if (sort === "price-desc") orderBy = { price: "desc" };
  if (sort === "rating") orderBy = { rating: "desc" };
  if (sort === "popular") orderBy = { reviewCount: "desc" };

  const products = await prisma.product.findMany({
    where,
    orderBy,
  });

  const categories = await prisma.product.findMany({
    where: { active: true },
    select: { category: true },
    distinct: ["category"],
  });

  const uniqueCategories = categories.map((c) => c.category);

  return (
    <div className="min-h-screen bg-gray-50">
      <div className="bg-primary-600 text-white py-10">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <h1 className="text-3xl font-bold">Pet Products Shop</h1>
          <p className="text-primary-100 mt-2">
            {products.length} products available{pet ? ` for ${pet}s` : ""}
          </p>
        </div>
      </div>

      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-10">
        <div className="flex flex-col lg:flex-row gap-8">
          <ShopFilters categories={uniqueCategories} currentPet={pet} currentCategory={category} currentSort={sort} />
          <div className="flex-1">
            {products.length === 0 ? (
              <div className="text-center py-20">
                <p className="text-gray-400 text-lg">No products found.</p>
              </div>
            ) : (
              <div className="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 gap-6">
                {products.map((product) => (
                  <ProductCard key={product.id} product={product} />
                ))}
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}
