import { Metadata } from "next";
import { Suspense } from "react";
import { Laptop } from "lucide-react";
import Link from "next/link";
import ProductGrid from "@/components/products/ProductGrid";
import ProductFilters from "@/components/products/ProductFilters";
import { prisma } from "@/lib/prisma";
import { serialize } from "@/lib/serialize";

export const metadata: Metadata = { title: "Laptops" };

export default async function LaptopsPage({ searchParams }: { searchParams: Promise<Record<string, string | undefined>> }) {
  const params = await searchParams;
  const page = parseInt(params.page || "1");
  const limit = 12;
  const sort = params.sort || "createdAt";
  const order = params.order || "desc";

  const where: Record<string,unknown> = { status: "ACTIVE", category: { slug: "laptops" } };
  if (params.brand) where.brand = { slug: params.brand };
  if (params.tag) where.tags = { some: { tag: params.tag } };
  if (params.minPrice || params.maxPrice) {
    where.price = {} as Record<string,unknown>;
    if (params.minPrice) (where.price as Record<string,unknown>).gte = parseFloat(params.minPrice);
    if (params.maxPrice) (where.price as Record<string,unknown>).lte = parseFloat(params.maxPrice);
  }

  const validSorts = ["price","createdAt","name"];
  const sortField = validSorts.includes(sort) ? sort : "createdAt";

  const [rawProducts, total, rawBrands] = await Promise.all([
    prisma.product.findMany({ where, include: { brand: true, category: true, reviews: { select: { rating: true } } }, orderBy: { [sortField]: order as "asc"|"desc" }, skip: (page-1)*limit, take: limit }),
    prisma.product.count({ where }),
    prisma.brand.findMany({ orderBy: { name: "asc" } }),
  ]);

  const products = serialize(rawProducts) as unknown as Parameters<typeof ProductGrid>[0]["products"];
  const brands = serialize(rawBrands) as unknown as { id: string; name: string; slug: string }[];
  const pages = Math.ceil(total / limit);

  return (
    <div className="max-w-7xl mx-auto px-4 py-8">
      <div className="mb-6">
        <div className="flex items-center gap-2 text-sm text-slate-500 mb-4">
          <Link href="/" className="hover:text-sky-600">Home</Link>
          <span>/</span>
          <span className="text-slate-800 font-medium">Laptops</span>
        </div>
        <div className="flex items-center gap-3">
          <div className="w-10 h-10 rounded-xl bg-sky-100 flex items-center justify-center">
            <Laptop className="w-5 h-5 text-sky-600" />
          </div>
          <div>
            <h1 className="text-2xl font-black text-slate-900">Laptops</h1>
            <p className="text-slate-500 text-sm">{total} laptops in stock</p>
          </div>
        </div>
      </div>
      <div className="flex gap-6">
        <Suspense><ProductFilters brands={brands} /></Suspense>
        <div className="flex-1 min-w-0">
          <ProductGrid products={products} cols={3} />
          {pages > 1 && (
            <div className="flex justify-center gap-2 mt-8">
              {Array.from({ length: pages }, (_, i) => i + 1).map((p) => (
                <a key={p} href={`?${new URLSearchParams({ ...params, page: String(p) })}`}
                  className={`w-10 h-10 rounded-xl flex items-center justify-center text-sm font-bold transition-all ${p === page ? "bg-sky-500 text-white" : "bg-white border border-slate-200 text-slate-600 hover:border-sky-300"}`}>
                  {p}
                </a>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
