import type { Metadata } from "next";
import Link from "next/link";
import Image from "next/image";
import { ShoppingCart, Star, Package } from "lucide-react";
import { db } from "@/lib/db";
import ShopSlider from "@/components/shop/ShopSlider";

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

export default async function ShopPage({
  searchParams,
}: {
  searchParams: Promise<{ cat?: string; q?: string }>;
}) {
  const sp = await searchParams;
  const catSlug = sp.cat ?? "";
  const q = sp.q ?? "";

  const [products, categories, slides] = await Promise.all([
    db.product.findMany({
      where: {
        isActive: true,
        ...(catSlug ? { category: { slug: catSlug } } : {}),
        ...(q ? { name: { contains: q } } : {}),
      },
      include: {
        images: { orderBy: { sortOrder: "asc" }, take: 1 },
        category: true,
      },
      orderBy: { createdAt: "desc" },
    }),
    db.productCategory.findMany({ orderBy: { name: "asc" } }),
    db.shopSlide.findMany({ where: { isActive: true }, orderBy: { sortOrder: "asc" } }),
  ]);

  const featured = products.filter(p => p.isFeatured);

  return (
    <div className="min-h-screen bg-neutral-50">
      {slides.length > 0 && <ShopSlider slides={slides} />}

      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-10">

        {categories.length > 0 && (
          <div className="flex gap-3 flex-wrap mb-8">
            <Link href="/shop" className={`px-4 py-2 rounded-full text-sm font-medium border transition-colors ${!catSlug ? "bg-navy-700 text-white border-navy-700" : "bg-white text-neutral-600 border-neutral-200 hover:border-navy-400"}`}>
              All
            </Link>
            {categories.map(c => (
              <Link key={c.id} href={`/shop?cat=${c.slug}`}
                className={`px-4 py-2 rounded-full text-sm font-medium border transition-colors ${catSlug === c.slug ? "bg-navy-700 text-white border-navy-700" : "bg-white text-neutral-600 border-neutral-200 hover:border-navy-400"}`}>
                {c.name}
              </Link>
            ))}
          </div>
        )}

        {!catSlug && !q && featured.length > 0 && (
          <div className="mb-12">
            <h2 className="text-xl font-bold text-navy-800 mb-5 flex items-center gap-2">
              <Star size={18} className="text-amber-400" fill="currentColor" /> Featured Products
            </h2>
            <div className="grid sm:grid-cols-2 lg:grid-cols-4 gap-5">
              {featured.slice(0, 4).map(p => (
                <ProductCard key={p.id} product={p} />
              ))}
            </div>
          </div>
        )}

        <div className="flex items-center justify-between mb-5">
          <h2 className="text-xl font-bold text-navy-800">
            {catSlug ? (categories.find(c => c.slug === catSlug)?.name ?? "Products") : "All Products"}
            <span className="text-base font-normal text-neutral-400 ml-2">({products.length})</span>
          </h2>
          <form method="GET" action="/shop" className="flex gap-2">
            {catSlug && <input type="hidden" name="cat" value={catSlug} />}
            <input name="q" defaultValue={q} placeholder="Search products…" className="border border-neutral-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-navy-500 w-48" />
            <button type="submit" className="px-3 py-2 bg-navy-700 text-white text-sm rounded-lg hover:bg-navy-800">Search</button>
          </form>
        </div>

        {products.length === 0 ? (
          <div className="text-center py-20 text-neutral-400">
            <Package size={48} className="mx-auto mb-4 opacity-30" />
            <p className="text-lg font-medium">No products found</p>
            <Link href="/shop" className="mt-3 inline-block text-sm text-navy-600 hover:underline">Clear filters</Link>
          </div>
        ) : (
          <div className="grid sm:grid-cols-2 lg:grid-cols-4 gap-5">
            {products.map(p => (
              <ProductCard key={p.id} product={p} />
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

type CardProduct = {
  id: string; name: string; slug: string; price: unknown; isFeatured: boolean;
  category: { name: string } | null;
  images: { url: string }[];
};

function ProductCard({ product: p }: { product: CardProduct }) {
  return (
    <Link href={`/shop/${p.slug}`} className="group bg-white rounded-2xl border border-neutral-200 overflow-hidden hover:shadow-md hover:border-navy-200 transition-all">
      <div className="relative aspect-square bg-neutral-100 overflow-hidden">
        {p.images[0] ? (
          <Image src={p.images[0].url} alt={p.name} fill className="object-cover group-hover:scale-105 transition-transform duration-300" unoptimized />
        ) : (
          <div className="w-full h-full flex items-center justify-center text-neutral-300"><Package size={40} /></div>
        )}
        {p.isFeatured && (
          <span className="absolute top-2 left-2 bg-amber-400 text-amber-900 text-[10px] font-bold px-2 py-0.5 rounded-full">Featured</span>
        )}
      </div>
      <div className="p-4">
        {p.category && <div className="text-[10px] font-bold text-neutral-400 uppercase tracking-wide mb-1">{p.category.name}</div>}
        <h3 className="font-semibold text-navy-800 text-sm leading-snug mb-2 line-clamp-2">{p.name}</h3>
        <div className="flex items-center justify-between">
          <span className="text-base font-bold text-navy-700">${Number(p.price).toFixed(2)}</span>
          <span className="p-2 bg-navy-50 rounded-lg text-navy-600 group-hover:bg-navy-700 group-hover:text-white transition-colors">
            <ShoppingCart size={14} />
          </span>
        </div>
      </div>
    </Link>
  );
}
