import { Head, Link, usePage } from '@inertiajs/react';
import { ArrowRight, Check, MessageCircle, Package } from 'lucide-react';
import { useState } from 'react';
import ImageLightbox from '@/components/frontend/image-lightbox';
import { Button } from '@/components/ui/button';
import { useSettings } from '@/hooks/useSettings';

type Product = {
    id: number; name: string; slug: string; origin: string | null; variety: string | null; fermentation: string | null; grade: string | null; fat_content: string | null; bean_size: string | null; bean_count: string | null; moisture: string | null; defect: string | null; harvest_season: string | null; stock_kg: number | null; moq_kg: number | null; short_description: string | null; description: string | null; flavor_notes: string | null; image: string | null; gallery: { id: number; url: string }[]; category_name: string | null; category_slug: string | null; certifications: { id: number; title: string; logo: string | null }[];
};
type Props = { product: Product; related: { id: number; name: string; slug: string; image: string | null }[]; seo: { title: string; description: string; image: string | null } };

export default function ProductDetail({ product, related, seo }: Props) {
    const { props } = usePage();
    const locale = String(props.locale ?? 'id');
    const isEn = locale === 'en';
    const settings = useSettings();
    const [img, setImg] = useState(product.image);
    const gallery = product.gallery.length ? product.gallery : product.image ? [{ id: 0, url: product.image }] : [];
    const [lightboxIndex, setLightboxIndex] = useState<number | null>(null);

    const waNumber = (settings.social_whatsapp ?? '+62 812-3456-7890').replace(/[^0-9]/g, '');
    const waText = encodeURIComponent(
        isEn ? `Hello Cocoa Elfatih, I'm interested in ${product.name}. Please share quotation.` : `Halo Cocoa Elfatih, saya tertarik dengan ${product.name}. Minta penawaran.`,
    );
    const waLink = `https://wa.me/${waNumber}?text=${waText}`;

    return (
        <>
            <Head title={seo.title}>
                <meta name="description" content={seo.description} />
                {seo.image && <meta property="og:image" content={seo.image} />}
            </Head>
            <section className="bg-[#FFF9F5] dark:bg-[#1A120E]">
                <div className="mx-auto max-w-7xl px-4 py-4 sm:px-6 sm:py-6 lg:px-8">
                    <nav className="truncate text-xs text-[#6B5B4F] dark:text-white/80">
                        <Link href={`/${locale}`} className="hover:underline">{isEn ? 'Home' : 'Beranda'}</Link> /{' '}
                        <Link href={`/${locale}/produk`} className="hover:underline">{isEn ? 'Products' : 'Produk'}</Link> /{' '}
                        <span className="text-[#2B1B12] dark:text-white">{product.name}</span>
                    </nav>
                </div>
            </section>

            <section className="bg-white dark:bg-[#1A120E]">
                <div className="mx-auto grid max-w-7xl gap-6 px-4 py-6 sm:px-6 sm:py-8 lg:grid-cols-2 lg:gap-10 lg:px-8 lg:py-12">
                    <div className="min-w-0">
                        <div className="overflow-hidden rounded-2xl bg-[#F5EFE8] dark:bg-white/5">
                            {img ? (
                                <button type="button" onClick={() => setLightboxIndex(gallery.findIndex((g) => g.url === img) >= 0 ? gallery.findIndex((g) => g.url === img) : 0)} className="block w-full">
                                    <img src={img} alt={product.name} loading="lazy" className="aspect-video w-full object-cover transition hover:opacity-95" />
                                </button>
                            ) : (
                                <div className="flex aspect-video w-full items-center justify-center text-sm text-[#6B5B4F]">No image</div>
                            )}
                        </div>
                        {gallery.length > 1 && (
                            <div className="mt-3 flex gap-2 overflow-x-auto pb-1">
                                {gallery.map((g, idx) => (
                                    <button
                                        key={g.id}
                                        onClick={() => {
                                            setImg(g.url);
                                            setLightboxIndex(idx);
                                        }}
                                        className={`shrink-0 overflow-hidden rounded-xl border-2 ${img === g.url ? 'border-[#6B2F0B] dark:border-white' : 'border-transparent'}`}
                                    >
                                        <img src={g.url} alt="" loading="lazy" className="h-16 w-16 object-cover sm:h-20 sm:w-20" />
                                    </button>
                                ))}
                            </div>
                        )}
                        <ImageLightbox
                            images={gallery.map((g) => ({ id: g.id, url: g.url, alt: product.name }))}
                            openIndex={lightboxIndex}
                            onClose={() => setLightboxIndex(null)}
                            onNavigate={setLightboxIndex}
                            locale={locale}
                        />
                    </div>
                    <div className="min-w-0">
                        {product.category_name && <span className="rounded-full bg-[#FFF9F5] px-3 py-1 text-xs font-medium text-[#A05A2C] dark:bg-white/15 dark:text-white">{product.category_name}</span>}
                        <h1 className="mt-3 font-poppins text-2xl font-bold leading-tight text-[#2B1B12] sm:text-3xl dark:text-white">{product.name}</h1>
                        <p className="mt-2 text-sm leading-relaxed text-[#6B5B4F] dark:text-white/80">{product.short_description}</p>
                        <div className="mt-4 grid grid-cols-2 gap-2 rounded-2xl border bg-[#FFFBF7] p-4 sm:gap-3 dark:border-white/10 dark:bg-white/5">
                            <Spec label={isEn ? 'Origin' : 'Asal'} value={product.origin} />
                            <Spec label="Variety" value={product.variety} />
                            <Spec label={isEn ? 'Fermentation' : 'Fermentasi'} value={product.fermentation} />
                            <Spec label="Grade" value={product.grade} />
                            <Spec label="Fat Content" value={product.fat_content ? `${product.fat_content}%` : null} />
                            <Spec label="Bean Size" value={product.bean_size} />
                            <Spec label="Bean Count" value={product.bean_count} />
                            <Spec label="Moisture" value={product.moisture} />
                            <Spec label="Defect" value={product.defect} />
                            <Spec label={isEn ? 'Harvest' : 'Panen'} value={product.harvest_season} />
                            <Spec label={isEn ? 'Stock' : 'Stok'} value={product.stock_kg ? `${product.stock_kg} kg` : null} />
                            <Spec label="MOQ" value={product.moq_kg ? `${product.moq_kg} kg` : null} />
                            <div className="col-span-2 flex items-center gap-2 rounded-xl bg-[#6B2F0B] px-3 py-2 text-xs text-white">
                                <Package className="size-4 shrink-0" /> {isEn ? 'Price hidden — request quotation via RFQ.' : 'Harga disembunyikan — minta penawaran via RFQ.'}
                            </div>
                            {product.flavor_notes && <div className="col-span-2 text-xs text-[#6B5B4F] dark:text-white/80"><span className="font-semibold text-[#2B1B12] dark:text-white">Flavor:</span> {product.flavor_notes}</div>}
                        </div>
                        <div className="mt-5 flex flex-col gap-3 sm:flex-row sm:flex-wrap">
                            <Button asChild className="w-full sm:w-auto">
                                <Link href={`/${locale}/kontak?product=${product.id}`}>{isEn ? 'Request Quotation / Sample' : 'Minta Penawaran / Sampel'} <ArrowRight className="size-4" /></Link>
                            </Button>
                            <Button asChild variant="outline" className="w-full sm:w-auto">
                                <a href={waLink} target="_blank" rel="noopener noreferrer">
                                    <MessageCircle className="size-4" /> WhatsApp
                                </a>
                            </Button>
                        </div>
                        {product.certifications.length > 0 && (
                            <div className="mt-5">
                                <p className="text-xs font-semibold text-[#2B1B12] dark:text-white">{isEn ? 'Certifications' : 'Sertifikasi'}</p>
                                <div className="mt-2 flex flex-wrap gap-2">
                                    {product.certifications.map((c) => (
                                        <span key={c.id} className="inline-flex items-center gap-1 rounded-full border bg-white px-3 py-1 text-xs dark:border-white/10 dark:bg-white/5">
                                            <Check className="size-3 text-[#A05A2C]" /> {c.title}
                                        </span>
                                    ))}
                                </div>
                            </div>
                        )}
                    </div>
                </div>
                {product.description && (
                    <div className="mx-auto max-w-7xl px-4 pb-8 sm:px-6 lg:px-8">
                        <div className="prose prose-sm max-w-none dark:prose-invert" dangerouslySetInnerHTML={{ __html: product.description }} />
                    </div>
                )}
                {related.length > 0 && (
                    <div className="mx-auto max-w-7xl px-4 pb-10 sm:px-6 lg:px-8">
                        <div className="flex items-center justify-between">
                            <h3 className="font-poppins text-base font-semibold text-[#2B1B12] sm:text-lg dark:text-white">{isEn ? 'Related Products' : 'Produk Terkait'}</h3>
                            <Link href={`/${locale}/produk`} className="text-xs font-medium text-[#A05A2C] hover:underline sm:text-sm">
                                {isEn ? 'View all →' : 'Lihat semua →'}
                            </Link>
                        </div>
                        <div className="mt-4 grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
                            {related.map((r) => (
                                <Link key={r.id} href={`/${locale}/produk/${r.slug}`} className="group overflow-hidden rounded-2xl border bg-white shadow-sm transition hover:-translate-y-0.5 hover:shadow-md dark:border-white/10 dark:bg-white/5">
                                    <div className="aspect-video overflow-hidden bg-[#F5EFE8] dark:bg-white/5">
                                        {r.image ? (
                                            <img src={r.image} alt={r.name} loading="lazy" className="h-full w-full object-cover transition group-hover:scale-105" />
                                        ) : (
                                            <img src="/assets-elfatih/image-default.png" alt={r.name} loading="lazy" className="h-full w-full object-cover" />
                                        )}
                                    </div>
                                    <div className="flex items-center justify-between gap-2 p-4">
                                        <p className="line-clamp-1 font-poppins text-sm font-semibold text-[#2B1B12] dark:text-white">{r.name}</p>
                                        <ArrowRight className="size-4 shrink-0 text-[#A05A2C] transition group-hover:translate-x-0.5" />
                                    </div>
                                </Link>
                            ))}
                        </div>
                    </div>
                )}
            </section>
        </>
    );
}

function Spec({ label, value }: { label: string; value: string | null }) {
    if (!value) {
return <div className="text-xs text-[#6B5B4F]/60 dark:text-white/40">{label}: —</div>;
}

    return (
        <div className="min-w-0 text-xs">
            <span className="font-semibold text-[#2B1B12] dark:text-white">{label}:</span> <span className="break-words text-[#6B5B4F] dark:text-white/85">{value}</span>
        </div>
    );
}
