import Link from "next/link";
import { notFound, permanentRedirect } from "next/navigation";
import { getProduct, type Product } from "@/lib/api";
import PdpBuy from "@/components/PdpBuy";
import PdpTabs from "@/components/PdpTabs";
import ProductCard from "@/components/ProductCard";
import { SITE_URL } from "@/lib/site";

export const revalidate = 300;

function slugify(s: string) {
  return (s || "").toLowerCase().trim().replace(/[^a-z0-9]+/g, "-").replace(/(^-|-$)/g, "");
}

const plain = (html?: string | null) => (html || "").replace(/<[^>]+>/g, " ").replace(/&nbsp;/g, " ").replace(/\s+/g, " ").trim();

export async function generateMetadata({ params }: { params: Promise<{ slug: string }> }) {
  const { slug } = await params;
  const data = await getProduct(slug);
  if (!data?.product) return { title: "Product — Awafi" };
  const p = data.product;
  const title = p.metaTitle || `${p.name} | Wholesale UAE | Awafi Drugstore`;
  return {
    // absolute: the product's own title tag, not the site template
    title: { absolute: title },
    description: describe(p),
    keywords: p.keywords || undefined,
    alternates: { canonical: `/portal/product/${p.slug}` },
    openGraph: { title, description: describe(p), images: p.image ? [p.image] : undefined },
  };
}

/** A description unique to the product: its own copy, the admin meta description, or one built from its details. */
function describe(p: Product) {
  const own = plain(p.desc);
  if (own) return own.length > 160 ? `${own.slice(0, 157).replace(/\s+\S*$/, "")}…` : own;
  if (p.metaDescription) return p.metaDescription;
  const cat = p.categoryLabel || p.parentCategoryLabel;
  return `Buy ${p.name}${cat ? ` (${cat})` : ""} wholesale from Awafi Drugstore — trade pricing and delivery to pharmacies and clinics across the UAE.`;
}

export default async function ProductPage({ params }: { params: Promise<{ slug: string }> }) {
  const { slug } = await params;
  const data = await getProduct(slug);
  if (data?.redirect) permanentRedirect(`/portal/product/${data.redirect}`);
  if (!data?.product) notFound();
  const { product: p, related } = data;
  const discount = p.mrp && p.mrp > p.price ? Math.round((1 - p.price / p.mrp) * 100) : 0;
  const catName = p.parentCategoryLabel || p.categoryLabel || "Catalogue";
  const images = [p.image, ...(p.gallery ?? [])].filter((g, i, all): g is string => !!g && all.indexOf(g) === i);
  const alt = (i: number) => `${p.name}${p.variant ? ` in ${p.variant}` : ""}${i ? ` — view ${i + 1}` : ""}`;
  const url = `${SITE_URL}/portal/product/${p.slug}`;
  const availability =
    p.inStock === false ? "https://schema.org/OutOfStock" : p.inStock ? "https://schema.org/InStock" : undefined;
  const schema = {
    "@context": "https://schema.org",
    "@type": "Product",
    name: p.name,
    ...(p.sku ? { sku: p.sku } : {}),
    ...(p.supplierCode ? { mpn: p.supplierCode } : {}),
    ...(p.brand ? { brand: { "@type": "Brand", name: p.brand } } : {}),
    ...(images.length ? { image: images } : {}),
    description: describe(p),
    ...(p.categoryLabel || p.category ? { category: p.categoryLabel || p.category } : {}),
    ...(p.variant ? { color: p.variant } : {}),
    ...(p.size ? { size: p.size } : {}),
    url,
    offers: {
      "@type": "Offer",
      priceCurrency: "AED",
      price: p.price,
      url,
      ...(availability ? { availability } : {}),
      ...(p.minOrder ? { eligibleQuantity: { "@type": "QuantitativeValue", minValue: p.minOrder } } : {}),
      seller: { "@type": "Organization", name: "Awafi Drugstore" },
    },
  };

  const stockLabel =
    p.inStock === false ? "Out of stock" : p.stock != null ? `In stock (${p.stock} units)` : "Available to order";

  return (
    <>
      <script type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify(schema).replace(/</g, "\\u003c") }} />
      <div className="pb-shell">
        <nav className="pb-crumbs pb-crumbs--pdp" aria-label="Breadcrumb">
          <Link href="/portal">Home</Link><span>/</span>
          {p.parentCategory ? <Link href={`/portal/${p.parentCategory}`}>{catName}</Link> : <span>{catName}</span>}
          <span>/</span>
          <span className="pb-crumbs-current">{p.name}</span>
        </nav>
      </div>

      <section className="pb-shell pb-pdp">
        <div className="pb-pdp-gallery">
          <div className="pb-pdp-main">
            {discount > 0 && <span className="pb-badge pb-badge--sale">-{discount}%</span>}
            {/* eslint-disable-next-line @next/next/no-img-element */}
            {p.image && <img className="pb-pdp-img" src={p.image} alt={alt(0)} />}
          </div>
          {images.length > 1 && (
            <div className="pb-pdp-thumbs">
              {images.slice(0, 4).map((g, i) => (
                <button className={`pb-pdp-thumb${i === 0 ? " is-active" : ""}`} key={i} aria-label={`Show ${alt(i)}`}>
                  {/* eslint-disable-next-line @next/next/no-img-element */}
                  <img src={g} alt={alt(i)} />
                </button>
              ))}
            </div>
          )}
        </div>

        <div className="pb-pdp-info">
          {p.brand ? <Link href={`/portal/brand/${slugify(p.brand)}`} className="pb-pdp-brand">{p.brand}</Link> : <span className="pb-pdp-brand">Awafi</span>}
          <h1 className="pb-pdp-title">{p.name}</h1>

          <div className="pb-pdp-price">
            <span className="pb-pdp-price-now">AED {p.price}</span>
            {p.mrp && p.mrp > p.price && (
              <>
                <span className="pb-pdp-price-was">AED {p.mrp}</span>
                <span className="pb-pdp-save">Save {discount}%</span>
              </>
            )}
            <span className="pb-pdp-vat">excl. VAT · trade price</span>
          </div>

          <PdpBuy p={p} />

          <ul className="pb-pdp-meta">
            {p.sku && <li><span>SKU</span><strong>{p.sku}</strong></li>}
            {p.supplierCode && <li><span>Manufacturer code</span><strong>{p.supplierCode}</strong></li>}
            {p.size && <li><span>Size</span><strong>{p.size}</strong></li>}
            <li><span>Case size</span><strong>{p.caseSize ? `${p.caseSize} units` : "On request"}</strong></li>
            <li><span>Minimum order</span><strong>{p.minOrder ? `${p.minOrder} units` : "1 unit"}</strong></li>
            <li><span>Stock</span><strong className={p.inStock === false ? "" : "pb-instock"}>{stockLabel}</strong></li>
            <li><span>Brand</span><strong>{p.brand || "Awafi"}</strong></li>
            <li><span>Category</span><strong>{p.categoryLabel || catName}</strong></li>
          </ul>

          <div className="pb-pdp-assure">
            <div><svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="1.7"><path d="M12 3l7 3v6c0 5-3 7.5-7 9-4-1.5-7-4-7-9V6l7-3Z" /></svg> 100% authentic</div>
            <div><svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="1.7"><path d="M3 7h13v10H3zM16 10h3l2 3v4h-5" strokeLinejoin="round" /></svg> UAE-wide delivery</div>
            <div><svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="1.7"><path d="M12 2v20M5 6h9a3 3 0 0 1 0 6H7a3 3 0 0 0 0 6h10" strokeLinecap="round" /></svg> Trade pricing</div>
          </div>
        </div>
      </section>

      <section className="pb-shell">
        <PdpTabs p={p} />
      </section>

      {related.length > 0 && (
        <section className="pb-section">
          <div className="pb-shell">
            <div className="pb-section-head"><h2>You may also like</h2></div>
            <div className="pb-grid">
              {related.slice(0, 6).map((r) => (
                <ProductCard p={r} key={r.id} />
              ))}
            </div>
          </div>
        </section>
      )}
      <div className="pb-section-spacer" />
    </>
  );
}
