import { notFound } from 'next/navigation';
import Link from 'next/link';
import Image from 'next/image';
import {
    getProductBySlug, getProducts, productImage, productCategory, plainText,
} from '@/lib/wp';
import { Button } from '@/components/ui/button';
import { Icon, WhatsappGlyph } from '@/components/icons';
import { ProductCard, type ProductCardItem } from '@/components/product-card';
import { waProductQuote } from '@/lib/whatsapp';
import { site } from '@/lib/site';
import type { Metadata } from 'next';

export const revalidate = 600;

interface Props { params: Promise<{ slug: string }>; }

export async function generateMetadata({ params }: Props): Promise<Metadata> {
    const { slug } = await params;
    const p = await getProductBySlug(slug).catch(() => null);
    if (!p) return { title: 'Product not found' };
    const title = p.title.rendered.replace(/&amp;/g, '&');
    const desc = p.excerpt ? plainText(p.excerpt.rendered, 160) : `Request a quote for ${title} from ${site.brand}.`;
    return {
        title,
        description: desc,
        openGraph: {
            title, description: desc,
            images: productImage(p, 'large') ? [productImage(p, 'large')] : [],
        },
    };
}

export default async function ProductPage({ params }: Props) {
    const { slug } = await params;
    const p = await getProductBySlug(slug);
    if (!p) notFound();

    const title = p.title.rendered.replace(/&amp;/g, '&');
    const img = productImage(p, 'large');
    const cat = productCategory(p);
    const description = p.content ? p.content.rendered : (p.excerpt?.rendered ?? '');

    // Related — same category, exclude current
    const related = await getProducts({ perPage: 8 }).catch(() => []);
    const relatedCards: ProductCardItem[] = related
        .filter((r) => r.slug !== p.slug)
        .slice(0, 4)
        .map((r) => ({
            slug: r.slug,
            title: r.title.rendered.replace(/&amp;/g, '&'),
            image: productImage(r, 'medium_large'),
            category: productCategory(r),
            inStock: true,
        }));

    return (
        <>
            {/* Hero band with breadcrumb */}
            <section className="bg-mesh-steel bg-noise pt-12 pb-8 border-b border-white/5">
                <div className="container-jt">
                    <nav className="text-xs font-mono uppercase tracking-widest text-steel-400 mb-4">
                        <Link href="/" className="hover:text-orange-500">Home</Link>
                        <span className="mx-2">/</span>
                        <Link href="/products" className="hover:text-orange-500">Shop</Link>
                        {cat && (<><span className="mx-2">/</span><span className="text-steel-300">{cat}</span></>)}
                    </nav>
                </div>
            </section>

            <section className="bg-ink-950 py-12 lg:py-20">
                <div className="container-jt grid lg:grid-cols-[1.3fr_1fr] gap-10 lg:gap-16">
                    {/* Gallery */}
                    <div className="lg:sticky lg:top-24 self-start">
                        <div className="relative aspect-square bg-white rounded-2xl overflow-hidden border border-white/5">
                            {img ? (
                                <Image
                                    src={img}
                                    alt={title}
                                    fill
                                    sizes="(max-width: 1024px) 100vw, 720px"
                                    priority
                                    className="object-contain p-8"
                                />
                            ) : (
                                <div className="w-full h-full flex items-center justify-center text-steel-300">
                                    <Icon.Cog className="w-32 h-32" />
                                </div>
                            )}
                            <span className="absolute top-4 left-4 inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full bg-success/15 text-emerald-300 border border-success/40 font-mono text-[11px] uppercase tracking-widest">
                                <span className="w-1.5 h-1.5 rounded-full bg-current" /> In Stock
                            </span>
                        </div>
                    </div>

                    {/* Sidebar */}
                    <div>
                        {cat && (
                            <span className="font-mono text-xs uppercase tracking-widest text-orange-500 mb-3 inline-block">{cat}</span>
                        )}
                        <h1 className="font-display text-white text-[clamp(2rem,4vw,3.25rem)] leading-tight mb-5">{title}</h1>

                        {p.excerpt?.rendered && (
                            <p className="text-steel-300 text-base leading-relaxed mb-8">
                                {plainText(p.excerpt.rendered, 280)}
                            </p>
                        )}

                        {/* Spec card */}
                        <div className="glass rounded-xl p-5 mb-6">
                            <h3 className="font-mono text-xs uppercase tracking-widest text-orange-500 mb-4 flex items-center gap-2">
                                <Icon.Bolt className="w-4 h-4" /> Quick Specs
                            </h3>
                            <ul className="text-sm space-y-2.5">
                                <SpecRow label="Category" value={cat || '—'} />
                                <SpecRow label="Availability" value="In stock — Industrial Area" />
                                <SpecRow label="Warranty" value="Manufacturer terms" />
                                <SpecRow label="Delivery" value="Same/next day in Kampala" />
                            </ul>
                        </div>

                        {/* CTAs */}
                        <div className="flex flex-col gap-3 mb-6">
                            <Button asChild size="xl" variant="primary" className="w-full">
                                <Link href={`/quote?product=${encodeURIComponent(title)}`}>
                                    <Icon.FileText className="w-4 h-4" /> Request Quotation
                                </Link>
                            </Button>
                            <div className="grid grid-cols-2 gap-3">
                                <Button asChild size="lg" variant="whatsapp">
                                    <a href={waProductQuote(title)} target="_blank" rel="noopener">
                                        <WhatsappGlyph className="w-4 h-4" /> WhatsApp
                                    </a>
                                </Button>
                                <Button asChild size="lg" variant="dark">
                                    <a href={`tel:${site.phone}`}>
                                        <Icon.Phone className="w-4 h-4" /> Call
                                    </a>
                                </Button>
                            </div>
                        </div>

                        {/* Trust list */}
                        <ul className="text-sm space-y-2 text-steel-300">
                            <li className="flex items-center gap-2"><Icon.Check className="w-4 h-4 text-success" /> Genuine OEM unit</li>
                            <li className="flex items-center gap-2"><Icon.Check className="w-4 h-4 text-success" /> Spare parts stocked locally</li>
                            <li className="flex items-center gap-2"><Icon.Check className="w-4 h-4 text-success" /> On-site commissioning available</li>
                        </ul>
                    </div>
                </div>
            </section>

            {/* Description */}
            {description && (
                <section className="bg-ink-950 pb-16">
                    <div className="container-jt max-w-4xl">
                        <h2 className="font-display text-white text-3xl mb-6">Overview</h2>
                        <div
                            className="prose prose-invert prose-headings:font-display prose-headings:uppercase prose-a:text-orange-500 max-w-none text-steel-200"
                            dangerouslySetInnerHTML={{ __html: description }}
                        />
                    </div>
                </section>
            )}

            {/* Related */}
            {relatedCards.length > 0 && (
                <section className="section-pad bg-mesh-light bg-noise">
                    <div className="container-jt">
                        <h2 className="font-display text-white text-3xl mb-8">Related Products</h2>
                        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4 sm:gap-5 lg:gap-6">
                            {relatedCards.map((r) => <ProductCard key={r.slug} p={r} />)}
                        </div>
                    </div>
                </section>
            )}

            {/* Product JSON-LD */}
            <script
                type="application/ld+json"
                dangerouslySetInnerHTML={{
                    __html: JSON.stringify({
                        '@context': 'https://schema.org',
                        '@type': 'Product',
                        name: title,
                        image: img || undefined,
                        description: p.excerpt ? plainText(p.excerpt.rendered, 280) : title,
                        category: cat,
                        brand: { '@type': 'Brand', name: site.brand },
                        offers: {
                            '@type': 'Offer',
                            availability: 'https://schema.org/InStock',
                            priceSpecification: { '@type': 'PriceSpecification', description: 'Request a Quote' },
                            seller: { '@type': 'Organization', name: site.brand },
                            businessFunction: 'https://purl.org/goodrelations/v1#Sell',
                        },
                    }),
                }}
            />
        </>
    );
}

function SpecRow({ label, value }: { label: string; value: string }) {
    return (
        <li className="flex items-baseline justify-between gap-3 py-1.5 border-b border-white/5 last:border-0">
            <span className="text-steel-400">{label}</span>
            <span className="text-white font-medium text-right">{value}</span>
        </li>
    );
}
