import { Metadata } from "next";
import { Suspense } from "react";
import { Smartphone } 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: "iPhones" };

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

  const where: Record<string,unknown> = { status: "ACTIVE", category: { slug: "iphones" } };
  if (params.tag) where.tags = { some: { tag: params.tag } };
  if (params.condition) where.condition = params.condition;
  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 [rawProducts, total] = await Promise.all([
    prisma.product.findMany({ where, include: { brand: true, category: true, reviews: { select: { rating: true } } }, orderBy: { createdAt: "desc" }, skip: (page-1)*limit, take: limit }),
    prisma.product.count({ where }),
  ]);

  const products = serialize(rawProducts) as unknown as Parameters<typeof ProductGrid>[0]["products"];
  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">iPhones</span>
        </div>
        <div className="flex items-center gap-3">
          <div className="w-10 h-10 rounded-xl bg-indigo-100 flex items-center justify-center">
            <Smartphone className="w-5 h-5 text-indigo-600" />
          </div>
          <div>
            <h1 className="text-2xl font-black text-slate-900">iPhones</h1>
            <p className="text-slate-500 text-sm">{total} iPhones in stock</p>
          </div>
        </div>
      </div>

      {/* iPhone Series quick filters */}
      <div className="flex gap-2 flex-wrap mb-6">
        {[
          { label: "All iPhones", tag: null },
          { label: "iPhone 16 Series", tag: "iphone-16" },
          { label: "iPhone 15 Series", tag: "iphone-15" },
          { label: "iPhone 14 Series", tag: "iphone-14" },
        ].map((f) => (
          <Link key={f.label} href={f.tag ? `/iphones?tag=${f.tag}` : "/iphones"}
            className={`px-4 py-2 rounded-xl text-sm font-medium transition-all ${params.tag === f.tag || (!params.tag && !f.tag) ? "bg-sky-500 text-white" : "bg-white border border-slate-200 text-slate-600 hover:border-sky-300"}`}>
            {f.label}
          </Link>
        ))}
      </div>

      <div className="flex gap-6">
        <Suspense><ProductFilters 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 ${p === page ? "bg-sky-500 text-white" : "bg-white border border-slate-200 text-slate-600"}`}>
                  {p}
                </a>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
