import Link from "next/link";
import { notFound } from "next/navigation";
import { and, desc, eq, ne } from "drizzle-orm";
import { db } from "@/db";
import { products, categories, reviews } from "@/db/schema";
import { sellable } from "@/lib/data";
import { ugx } from "@/lib/format";
import { AddToCart, WishButton } from "@/components/store";
import { ProductGrid, ProductImage } from "@/components/ProductCard";
import { ReviewForm } from "@/components/forms";

async function get(slug: string) { const [p] = await db.select().from(products).where(and(eq(products.slug, slug), sellable)); return p; }

export async function generateMetadata({ params }: { params: Promise<{ slug: string }> }) {
  const p = await get((await params).slug);
  return p ? { title: p.name, description: p.description.slice(0, 160), alternates: { canonical: `/product/${p.slug}` }, openGraph: { images: p.image ? [p.image] : [] } } : {};
}

export default async function ProductPage({ params }: { params: Promise<{ slug: string }> }) {
  const p = await get((await params).slug);
  if (!p) notFound();
  const [cat] = p.categoryId ? await db.select().from(categories).where(eq(categories.id, p.categoryId)) : [];
  const revs = await db.select().from(reviews).where(and(eq(reviews.productId, p.id), eq(reviews.approved, true))).orderBy(desc(reviews.id));
  const related = p.categoryId ? await db.select().from(products).where(and(sellable, eq(products.categoryId, p.categoryId), ne(products.id, p.id))).limit(4) : [];
  const avg = revs.length ? revs.reduce((a, r) => a + r.rating, 0) / revs.length : 0;
  const off = p.comparePrice && p.comparePrice > p.price ? Math.round(((p.comparePrice - p.price) / p.comparePrice) * 100) : 0;
  const schema = { "@context": "https://schema.org", "@type": "Product", name: p.name, sku: p.sku, brand: p.brand ? { "@type": "Brand", name: p.brand } : undefined, image: p.image || undefined, description: p.description, offers: { "@type": "Offer", priceCurrency: "UGX", price: p.price, availability: p.stock > 0 ? "https://schema.org/InStock" : "https://schema.org/OutOfStock" }, ...(revs.length ? { aggregateRating: { "@type": "AggregateRating", ratingValue: avg.toFixed(1), reviewCount: revs.length } } : {}) };
  return (
    <div className="container-x py-8">
      <script type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify(schema) }} />
      <nav className="text-xs text-slate-500 mb-5"><Link href="/">Home</Link> / <Link href="/shop">Shop</Link>{cat && <> / <Link href={`/category/${cat.slug}`}>{cat.name}</Link></>} / <span className="text-ink">{p.name}</span></nav>
      <div className="grid lg:grid-cols-2 gap-10">
        <div className="card p-6 aspect-square relative overflow-hidden group">
          {off > 0 && <span className="absolute top-5 left-5 z-10 bg-red-500 text-white text-xs font-bold px-3 py-1 rounded-full">-{off}%</span>}
          <a href={p.image || "#"} target={p.image ? "_blank" : undefined} rel="noopener" className="block w-full h-full overflow-hidden rounded-xl cursor-zoom-in">
            <ProductImage src={p.image} alt={p.name} className="group-hover:scale-125 transition duration-500" />
          </a>
        </div>
        <div className="anim-fade-up">
          <span className="text-xs uppercase tracking-wider font-semibold text-slate-400">{p.brand}</span>
          <h1 className="text-2xl md:text-3xl font-extrabold mt-1 leading-tight">{p.name}</h1>
          <div className="text-sm text-slate-500 mt-2">SKU: {p.sku}{revs.length > 0 && <span className="ml-3 text-amber-500">{"★".repeat(Math.round(avg))} <span className="text-slate-400">({revs.length} reviews)</span></span>}</div>
          <div className="flex items-baseline gap-3 mt-5"><span className="text-3xl font-extrabold text-brand">{ugx(p.price)}</span>{off > 0 && <span className="line-through text-slate-400">{ugx(p.comparePrice!)}</span>}</div>
          <div className={`mt-2 text-sm font-semibold ${p.stock > 0 ? "text-brand" : "text-red-600"}`}>{p.stock > 0 ? (p.stock <= p.lowStock ? `Only ${p.stock} left in stock` : "In stock") : "Out of stock"}</div>
          <p className="mt-5 text-slate-600 leading-relaxed">{p.description}</p>
          {p.rxRequired ? (
            <div className="mt-6 p-5 rounded-2xl bg-softblue border border-royal/20">
              <p className="font-bold text-royal">Prescription required</p>
              <p className="text-sm text-slate-600 mt-1">This medicine can only be dispensed after a licensed pharmacist verifies a valid prescription.</p>
              <Link href="/prescription" className="btn btn-blue mt-4">Upload Prescription</Link>
            </div>
          ) : (
            <div className="mt-6 flex gap-3 items-center"><AddToCart id={p.id} qtyPicker disabled={p.stock <= 0} className="flex-1 max-w-md" /><WishButton id={p.id} className="!w-11 !h-11" /></div>
          )}
          <div className="mt-8 grid sm:grid-cols-3 gap-3 text-xs">
            {["🚚 Delivery available", "💬 Pharmacist advice", "🔒 Secure checkout"].map((t) => <div key={t} className="bg-mint rounded-xl p-3 font-semibold text-center">{t}</div>)}
          </div>
          <div className="mt-8 space-y-4">
            <details open className="card p-5"><summary className="font-bold cursor-pointer">Usage information</summary><p className="text-sm text-slate-600 mt-3">{p.usage}</p></details>
            <details className="card p-5"><summary className="font-bold cursor-pointer">Warnings & precautions</summary><p className="text-sm text-slate-600 mt-3">{p.warnings}</p></details>
          </div>
        </div>
      </div>
      <section className="mt-14 grid lg:grid-cols-2 gap-8">
        <div><h2 className="section-title !text-xl mb-4">Customer Reviews</h2>{revs.length ? revs.map((r) => <div key={r.id} className="border-b py-3"><div className="text-amber-500 text-sm">{"★".repeat(r.rating)}</div><div className="font-semibold text-sm">{r.name}</div><p className="text-sm text-slate-600">{r.comment}</p></div>) : <p className="text-sm text-slate-500">No reviews yet.</p>}</div>
        <ReviewForm productId={p.id} />
      </section>
      {related.length > 0 && <section className="mt-14"><h2 className="section-title !text-xl mb-5">Related Products</h2><ProductGrid items={related} /></section>}
    </div>
  );
}
