import Image from "next/image";
import Link from "next/link";
import { notFound } from "next/navigation";
import { setRequestLocale } from "next-intl/server";
import {
  ArrowLeft, ArrowRight, Check,
  MessageCircle, FileText,
} from "lucide-react";
import { cn } from "@/lib/utils";
import { ButtonLink } from "@/components/ui/button";
import { FadeIn } from "@/components/magicui/fade-in";
import { ProductGallery } from "@/components/products/product-gallery";
import { CONTACT_INFO, PRODUCTS } from "@/data/site-data";
import { getLocalizedProducts } from "@/data/localized-data";
import { productJsonLd, breadcrumbJsonLd } from "@/lib/jsonld";
import { JsonLd } from "@/components/seo/json-ld";
import { SITE_URL } from "@/lib/seo";

export function generateStaticParams() {
  return PRODUCTS.map((p) => ({ slug: p.slug }));
}
export const dynamicParams = false;

function getCategoryLabel(category: string, locale: string) {
  if (locale === "id") {
    switch (category) {
      case "All": return "Semua";
      case "Raw": return "Mentah";
      case "Processed": return "Olahan";
      case "Ingredients": return "Bahan Baku";
    }
  } else if (locale === "zh") {
    switch (category) {
      case "All": return "全部";
      case "Raw": return "毛燕/原料";
      case "Processed": return "净燕/加工";
      case "Ingredients": return "燕窝制品/配料";
    }
  }
  return category;
}

export default async function ProductDetailPage({
  params,
}: {
  params: Promise<{ locale: string; slug: string }>;
}) {
  const { locale, slug } = await params;
  setRequestLocale(locale);
  const l = (href: string) => `/${locale}${href}`;

  const products = getLocalizedProducts(locale);
  const product = products.find((p) => p.slug === slug);
  if (!product) notFound();

  const related = products.filter((p) => p.slug !== slug).slice(0, 3);

  return (
    <main>
      <JsonLd
        data={productJsonLd({
          name: product.name,
          description: product.description,
          image: product.image,
          slug: product.slug,
          locale,
        })}
      />
      <JsonLd
        data={breadcrumbJsonLd([
          { name: "Home", url: `${SITE_URL}/${locale}` },
          { name: "Products", url: `${SITE_URL}/${locale}/products` },
          { name: product.name, url: `${SITE_URL}/${locale}/products/${product.slug}` },
        ])}
      />
      {/* Breadcrumb */}
      <div className="border-b border-black/5 bg-white">
        <div className="mx-auto max-w-7xl px-4 py-3 sm:px-6 lg:px-8">
          <nav className="flex items-center gap-2 text-[11px] text-muted">
            <Link href={l("/")} className="transition-colors hover:text-gold">
              {locale === "id" ? "Beranda" : locale === "zh" ? "首页" : "Home"}
            </Link>
            <span className="text-black/20">/</span>
            <Link href={l("/products")} className="transition-colors hover:text-gold">
              {locale === "id" ? "Produk" : locale === "zh" ? "产品" : "Products"}
            </Link>
            <span className="text-black/20">/</span>
            <span className="font-semibold text-ink">{product.name}</span>
          </nav>
        </div>
      </div>

      {/* Main Detail */}
      <section className="bg-gold-bg py-12 sm:py-16">
        <div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8">
          <div className="grid grid-cols-1 items-start gap-10 lg:grid-cols-2">

            {/* Gallery (client island) */}
            <FadeIn direction="left">
              <ProductGallery
                gallery={[...product.gallery]}
                name={product.name}
                categoryLabel={getCategoryLabel(product.category, locale)}
              />
            </FadeIn>

            {/* Info */}
            <FadeIn direction="right" delay={150}>
              <div className="flex flex-col gap-7">
                <div>
                  <h1 className="font-serif text-3xl font-bold tracking-tight text-ink sm:text-4xl lg:text-5xl">
                    {product.name}
                  </h1>
                  <p className="mt-4 text-sm leading-relaxed text-muted sm:text-base">
                    {product.longDescription}
                  </p>
                </div>
                <div className="h-px bg-black/6" />
                <div>
                  <p className="mb-4 text-[10px] font-bold uppercase tracking-[0.25em] text-gold">
                    {locale === "id" ? "Fitur Utama" : locale === "zh" ? "主要特点" : "Key Features"}
                  </p>
                  <ul className="grid grid-cols-1 gap-2.5 sm:grid-cols-2">
                    {product.features.map((feature) => (
                      <li key={feature} className="flex items-start gap-2.5 text-xs leading-relaxed text-muted">
                        <span className="mt-0.5 flex h-4 w-4 shrink-0 items-center justify-center rounded-full bg-gold/10">
                          <Check className="h-2.5 w-2.5 text-gold" />
                        </span>
                        {feature}
                      </li>
                    ))}
                  </ul>
                </div>
                <div className="h-px bg-black/6" />
                <div className="flex flex-wrap gap-3">
                  <ButtonLink href={CONTACT_INFO.whatsapp} target="_blank" rel="noopener noreferrer">
                    <MessageCircle className="h-3.5 w-3.5" />
                    {locale === "id" ? "HUBUNGI WHATSAPP" : locale === "zh" ? "联系 WHATSAPP" : "WHATSAPP US"}
                  </ButtonLink>
                  <ButtonLink href={l("/#contact")} variant="outline">
                    <FileText className="h-3.5 w-3.5" />
                    {locale === "id" ? "MINTA KATALOG" : locale === "zh" ? "索取目录" : "REQUEST CATALOG"}
                  </ButtonLink>
                </div>
              </div>
            </FadeIn>
          </div>
        </div>
      </section>

      {/* Specifications */}
      <section className="bg-white py-14 sm:py-20">
        <div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8">
          <FadeIn>
            <p className="mb-2 text-center text-xs font-bold uppercase tracking-[0.25em] text-gold">
              {locale === "id" ? "Data Teknis" : locale === "zh" ? "技术数据" : "Technical Data"}
            </p>
            <h2 className="mb-10 text-center font-serif text-2xl font-bold text-ink sm:text-3xl">
              {locale === "id" ? "Spesifikasi Produk" : locale === "zh" ? "产品规格" : "Product Specifications"}
            </h2>
          </FadeIn>
          <FadeIn delay={80}>
            <div className="mx-auto max-w-2xl overflow-hidden rounded-2xl border border-black/5 bg-white shadow-sm">
              {Object.entries(product.specs).map(([key, value], i) => (
                <div
                  key={key}
                  className={cn(
                    "flex items-center justify-between gap-6 px-6 py-4",
                    i !== Object.keys(product.specs).length - 1 && "border-b border-black/5",
                    i % 2 === 1 && "bg-gold-bg/40"
                  )}
                >
                  <span className="text-xs font-bold uppercase tracking-widest text-ink">{key}</span>
                  <span className="text-right text-sm text-muted">{value}</span>
                </div>
              ))}
            </div>
          </FadeIn>

          {/* Variants (sub-products) */}
          {product.variants && product.variants.length > 0 && (
            <FadeIn delay={120}>
              <div className="mt-14">
                <p className="mb-6 text-center text-xs font-bold uppercase tracking-[0.25em] text-gold">
                  {locale === "id" ? "Variasi Produk" : locale === "zh" ? "产品规格型号" : "Product Variants"}
                </p>
                <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
                  {product.variants.map((variant: {
                    name: string;
                    nameCn?: string;
                    size?: string;
                    netto?: string;
                    cleanliness?: string;
                    quantity500g?: string;
                    quantity100g?: string;
                  }) => (
                    <div
                      key={variant.name}
                      className="rounded-2xl border border-gold/20 bg-white p-5 shadow-sm"
                    >
                      <div className="mb-3 border-b border-black/5 pb-3">
                        <h3 className="font-serif text-base font-bold text-ink">
                          {locale === "zh" && variant.nameCn ? variant.nameCn : variant.name}
                        </h3>
                      </div>
                      <div className="grid grid-cols-2 gap-x-4 gap-y-3">
                        <div>
                          <p className="text-[10px] font-bold uppercase tracking-wider text-gold">
                            {locale === "zh" ? "燕盏高度" : locale === "id" ? "Ukuran" : "Size"}
                          </p>
                          <p className="text-sm font-semibold text-ink">{variant.size ?? "—"}</p>
                        </div>
                        {variant.cleanliness ? (
                          <div>
                            <p className="text-[10px] font-bold uppercase tracking-wider text-gold">
                              {locale === "zh" ? "干净度" : locale === "id" ? "Tingkat Kebersihan" : "Cleanliness"}
                            </p>
                            <p className="text-sm font-semibold text-ink">{variant.cleanliness}</p>
                          </div>
                        ) : (
                          <div>
                            <p className="text-[10px] font-bold uppercase tracking-wider text-gold">
                              {locale === "zh" ? "单盏克数" : locale === "id" ? "Berat" : "Netto"}
                            </p>
                            <p className="text-sm font-semibold text-ink">{variant.netto ?? "—"}</p>
                          </div>
                        )}
                        <div className="col-span-2">
                          <p className="text-[10px] font-bold uppercase tracking-wider text-gold">
                            {variant.quantity500g
                              ? locale === "zh" ? "盏数(500克)" : locale === "id" ? "Jumlah (500gr)" : "Quantity (500 gr)"
                              : locale === "zh" ? "盏数(100克)" : locale === "id" ? "Jumlah (100gr)" : "Quantity (100 gr)"}
                          </p>
                          <p className="text-sm font-semibold text-ink">
                            {variant.quantity500g ?? variant.quantity100g ?? "—"}
                          </p>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            </FadeIn>
          )}
        </div>
      </section>

      {/* Related */}
      <section className="bg-gold-bg py-14 sm:py-20">
        <div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8">
          <FadeIn>
            <div className="mb-10 flex items-end justify-between">
              <div>
                <p className="mb-1 text-xs font-bold uppercase tracking-[0.25em] text-gold">
                  {locale === "id" ? "Jelajahi Lebih Lanjut" : locale === "zh" ? "探索更多" : "Explore More"}
                </p>
                <h2 className="font-serif text-2xl font-bold text-ink sm:text-3xl">
                  {locale === "id" ? "Produk Lainnya" : locale === "zh" ? "其他产品" : "Other Products"}
                </h2>
              </div>
              <Link href={l("/products")} className="hidden items-center gap-1.5 text-xs font-bold tracking-wider text-muted transition-colors hover:text-gold sm:flex">
                {locale === "id" ? "Lihat Semua" : locale === "zh" ? "查看全部" : "View All"} <ArrowRight className="h-3.5 w-3.5" />
              </Link>
            </div>
          </FadeIn>
          <div className="grid grid-cols-1 gap-5 sm:grid-cols-2 lg:grid-cols-3">
            {related.map((item, index) => (
              <FadeIn key={item.slug} delay={index * 80} className="h-full">
                <Link href={l(`/products/${item.slug}`)} className="group block h-full">
                  <article className="flex h-full flex-col overflow-hidden rounded-2xl border border-black/5 bg-white shadow-sm transition-all duration-300 hover:-translate-y-1 hover:shadow-lg">
                    <div className="relative aspect-[4/3] overflow-hidden bg-cream">
                      <Image src={item.image} alt={item.name} fill
                        className="object-cover transition-transform duration-700 group-hover:scale-105"
                        sizes="(max-width: 640px) 100vw, (max-width: 1024px) 50vw, 33vw" />
                      <div className="absolute right-3 top-3">
                        <span className="rounded-full bg-white/90 px-2.5 py-1 text-[10px] font-bold tracking-wider text-gold backdrop-blur-sm">
                          {getCategoryLabel(item.category, locale)}
                        </span>
                      </div>
                    </div>
                    <div className="flex flex-1 flex-col gap-2 p-5">
                      <h3 className="font-serif text-lg font-bold text-ink transition-colors group-hover:text-gold">{item.name}</h3>
                      <p className="flex-1 text-xs leading-relaxed text-muted">{item.description}</p>
                      <div className="mt-2 flex items-center gap-1 text-[11px] font-bold tracking-wider text-gold transition-all group-hover:gap-2">
                        {locale === "id" ? "LIHAT DETAIL" : locale === "zh" ? "查看详情" : "VIEW DETAILS"}
                        <ArrowRight className="h-3 w-3 transition-transform group-hover:translate-x-0.5" />
                      </div>
                    </div>
                  </article>
                </Link>
              </FadeIn>
            ))}
          </div>
          <FadeIn>
            <div className="mt-10 text-center sm:hidden">
              <ButtonLink href={l("/products")} variant="outline">
                <ArrowLeft className="h-3.5 w-3.5" />
                {locale === "id" ? "SEMUA PRODUK" : locale === "zh" ? "所有产品" : "ALL PRODUCTS"}
              </ButtonLink>
            </div>
          </FadeIn>
        </div>
      </section>
    </main>
  );
}
