import Link from "next/link";
import { and, asc, desc, eq, gt, ilike, isNotNull, or, gte, lte, type SQL } from "drizzle-orm";
import { db } from "@/db";
import { products } from "@/db/schema";
import { getCategories, sellable } from "@/lib/data";
import { ProductGrid } from "@/components/ProductCard";

export type ShopParams = { q?: string; category?: string; offers?: string; featured?: string; best?: string; sort?: string; min?: string; max?: string; stock?: string };

export async function ShopView({ sp, title, forcedCategory }: { sp: ShopParams; title: string; forcedCategory?: string }) {
  const cats = await getCategories();
  const catSlug = forcedCategory || sp.category;
  const cat = cats.find((c) => c.slug === catSlug);
  const w: (SQL | undefined)[] = [sellable];
  if (sp.q) w.push(or(ilike(products.name, `%${sp.q}%`), ilike(products.brand, `%${sp.q}%`), ilike(products.description, `%${sp.q}%`)));
  if (cat) w.push(eq(products.categoryId, cat.id));
  if (sp.offers) w.push(and(isNotNull(products.comparePrice), gt(products.comparePrice, products.price)));
  if (sp.featured) w.push(eq(products.featured, true));
  if (sp.best) w.push(eq(products.bestSeller, true));
  if (sp.stock) w.push(gt(products.stock, 0));
  if (sp.min) w.push(gte(products.price, Number(sp.min)));
  if (sp.max) w.push(lte(products.price, Number(sp.max)));
  const order = sp.sort === "price_asc" ? asc(products.price) : sp.sort === "price_desc" ? desc(products.price) : sp.sort === "name" ? asc(products.name) : desc(products.id);
  const items = await db.select().from(products).where(and(...w)).orderBy(order).limit(200);
  const qs = (patch: Record<string, string | undefined>) => {
    const p = new URLSearchParams(Object.entries({ ...sp, ...patch }).filter(([, v]) => v) as [string, string][]);
    if (forcedCategory) p.delete("category");
    return "?" + p.toString();
  };
  return (
    <div className="container-x py-8">
      <nav className="text-xs text-slate-500 mb-3"><Link href="/">Home</Link> / <Link href="/shop">Shop</Link>{cat && <> / <span className="text-ink">{cat.name}</span></>}</nav>
      {cat?.image && forcedCategory ? (
        <div className="relative rounded-3xl overflow-hidden h-44 md:h-56 mb-8">
          {/* eslint-disable-next-line @next/next/no-img-element */}
          <img src={cat.image} alt={cat.name} className="absolute inset-0 w-full h-full object-cover anim-kenburns" />
          <div className="absolute inset-0 bg-gradient-to-r from-ink/80 to-transparent" />
          <div className="relative p-8 md:p-10 text-white"><h1 className="text-3xl font-extrabold">{cat.name}</h1><p className="mt-2 text-white/80 max-w-md text-sm">{cat.description}</p></div>
        </div>
      ) : <h1 className="section-title mb-6">{sp.q ? `Search results for “${sp.q}”` : title}</h1>}
      <div className="grid lg:grid-cols-[240px_1fr] gap-8">
        <aside className="space-y-6">
          <div className="card p-5">
            <h3 className="font-bold mb-3 text-sm">Categories</h3>
            <Link href={"/shop" + qs({ category: undefined })} className={`block py-1.5 text-sm ${!cat ? "text-brand font-semibold" : "hover:text-brand"}`}>All products</Link>
            {cats.map((c) => <Link key={c.id} href={`/category/${c.slug}`} className={`block py-1.5 text-sm ${cat?.id === c.id ? "text-brand font-semibold" : "hover:text-brand"}`}>{c.name}</Link>)}
          </div>
          <form className="card p-5 space-y-3">
            <h3 className="font-bold text-sm">Filter</h3>
            {sp.q && <input type="hidden" name="q" value={sp.q} />}
            {!forcedCategory && sp.category && <input type="hidden" name="category" value={sp.category} />}
            <div className="flex gap-2"><input name="min" defaultValue={sp.min} placeholder="Min UGX" className="input !text-xs" /><input name="max" defaultValue={sp.max} placeholder="Max UGX" className="input !text-xs" /></div>
            <label className="flex gap-2 text-sm"><input type="checkbox" name="offers" value="1" defaultChecked={!!sp.offers} /> On offer</label>
            <label className="flex gap-2 text-sm"><input type="checkbox" name="stock" value="1" defaultChecked={!!sp.stock} /> In stock only</label>
            <select name="sort" defaultValue={sp.sort} className="input !text-sm"><option value="">Newest</option><option value="price_asc">Price: low to high</option><option value="price_desc">Price: high to low</option><option value="name">Name A–Z</option></select>
            <button className="btn btn-green w-full !py-2">Apply</button>
          </form>
        </aside>
        <div><p className="text-sm text-slate-500 mb-4">{items.length} products</p><ProductGrid items={items} /></div>
      </div>
    </div>
  );
}
