import Link from "next/link";
import { ugx } from "@/lib/format";
import { AddToCart, WishButton } from "@/components/store";
import type { products } from "@/db/schema";

type P = typeof products.$inferSelect;

export function ProductImage({ src, alt, className = "" }: { src: string; alt: string; className?: string }) {
  if (!src) {
    return (
      <div className={`w-full h-full grid place-items-center bg-gradient-to-br from-mint to-softblue ${className}`}>
        <div className="text-center px-3">
          <svg className="mx-auto opacity-70" width="54" height="54" viewBox="0 0 24 24" fill="none" stroke="#079B49" strokeWidth="1.4"><rect x="6" y="3" width="12" height="18" rx="3" /><path d="M6 8h12M12 11v6M9 14h6" /></svg>
          <span className="mt-2 block text-[11px] font-semibold text-brand/80">Product image coming soon</span>
        </div>
      </div>
    );
  }
  // eslint-disable-next-line @next/next/no-img-element
  return <img src={src} alt={alt} loading="lazy" className={`w-full h-full object-contain ${className}`} />;
}

export function ProductCard({ p, rating }: { p: P; rating?: { avg: number; n: number } }) {
  const off = p.comparePrice && p.comparePrice > p.price ? Math.round(((p.comparePrice - p.price) / p.comparePrice) * 100) : 0;
  const stock = p.stock <= 0 ? ["Out of stock", "text-red-600"] : p.stock <= p.lowStock ? [`Only ${p.stock} left`, "text-amber-600"] : ["In stock", "text-brand"];
  return (
    <div className="card group flex flex-col overflow-hidden hover:-translate-y-1 hover:shadow-[0_18px_40px_-18px_rgba(32,43,56,.25)] transition duration-300 reveal">
      <div className="relative aspect-square bg-white p-4">
        {off > 0 && <span className="absolute top-3 left-3 z-10 bg-red-500 text-white text-[11px] font-bold px-2 py-1 rounded-full">-{off}%</span>}
        {p.rxRequired && <span className="absolute top-3 left-3 z-10 bg-royal text-white text-[11px] font-bold px-2 py-1 rounded-full">Rx</span>}
        <WishButton id={p.id} className="absolute top-3 right-3 z-10" />
        <Link href={`/product/${p.slug}`} className="block w-full h-full overflow-hidden rounded-xl">
          <ProductImage src={p.image} alt={p.name} className="group-hover:scale-105 transition duration-500" />
        </Link>
        <Link href={`/product/${p.slug}`} className="absolute inset-x-4 bottom-3 text-center text-xs font-semibold bg-white/95 border rounded-full py-1.5 opacity-0 group-hover:opacity-100 translate-y-2 group-hover:translate-y-0 transition">Quick View</Link>
      </div>
      <div className="p-4 pt-1 flex flex-col flex-1">
        <span className="text-[11px] uppercase tracking-wider text-slate-400 font-semibold">{p.brand || "Pharmacy"}</span>
        <Link href={`/product/${p.slug}`} className="mt-1 font-semibold text-sm leading-snug line-clamp-2 min-h-[2.5rem] hover:text-brand">{p.name}</Link>
        {rating && rating.n > 0 && <div className="text-xs text-amber-500 mt-1">{"★".repeat(Math.round(rating.avg))}<span className="text-slate-400"> ({rating.n})</span></div>}
        <div className="mt-2 flex items-baseline gap-2">
          <span className="text-lg font-extrabold text-ink">{ugx(p.price)}</span>
          {off > 0 && <span className="text-xs line-through text-slate-400">{ugx(p.comparePrice!)}</span>}
        </div>
        <span className={`text-xs font-medium mt-0.5 ${stock[1]}`}>{stock[0]}</span>
        <div className="mt-auto pt-3">
          {p.rxRequired ? <Link href="/prescription" className="btn btn-blue w-full !py-2.5">Upload Prescription</Link> : <AddToCart id={p.id} disabled={p.stock <= 0} label={p.stock <= 0 ? "Out of stock" : "Add to Cart"} />}
        </div>
      </div>
    </div>
  );
}

export function ProductGrid({ items }: { items: P[] }) {
  if (!items.length) return <p className="text-slate-500 py-10 text-center">No products found.</p>;
  return <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-3 sm:gap-5">{items.map((p) => <ProductCard key={p.id} p={p} />)}</div>;
}
