import Link from 'next/link';
import Image from 'next/image';
import type { Metadata } from 'next';
import {
  fetchProductBySlug,
  fetchProductVariants,
  fetchVariantPrice,
  fetchStockAvailability,
  fetchCategories,
  fetchBrands,
  formatPrice,
  calcGrossPrice,
} from '@/lib/api';
import ProductAddToCart from '@/components/cart/ProductAddToCart';
import ProductAttributes from '@/components/product/ProductAttributes';
import { formatRichText } from '@/lib/format-rich-text';

// Product data comes from the live backend; resolve it at request time.
export const dynamic = 'force-dynamic';

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

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { slug } = await params;
  const product = await fetchProductBySlug(slug);
  if (!product) return { title: 'Producto no encontrado' };
  return {
    title: product.seoTitle ?? product.name,
    description: product.seoDescription ?? product.description,
  };
}

export default async function ProductPage({ params }: Props) {
  const { slug } = await params;
  const [product, brands] = await Promise.all([
    fetchProductBySlug(slug),
    fetchBrands(),
  ]);

  if (!product) {
    return (
      <div className="max-w-7xl mx-auto px-4 py-16 text-center">
        <h1 className="text-2xl font-bold text-gray-900 mb-4">Producto no encontrado</h1>
        <p className="text-gray-500 mb-8">El producto que buscas no existe.</p>
        <Link href="/products" className="text-[#70ad47] font-medium hover:underline">
          Ver todos los productos →
        </Link>
      </div>
    );
  }

  const brand = brands.find((b) => b.id === product.brandId);

  // Get primary variant + price + stock
  const variants = await fetchProductVariants(product.id);
  const primaryVariant = variants[0];

  let price = null;
  let stock = null;
  if (primaryVariant) {
    [price, stock] = await Promise.all([
      fetchVariantPrice(primaryVariant.id),
      fetchStockAvailability(primaryVariant.id),
    ]);
  }

  // Build category links from all category IDs
  const tree = await fetchCategories();
  const flatCats: Array<{ id: string; name: string; slug: string; parentSlug?: string }> = [];
  function flatten(cats: typeof tree, parentSlug?: string) {
    for (const cat of cats) {
      flatCats.push({ id: cat.id, name: cat.name, slug: cat.slug, parentSlug });
      if (cat.children?.length) flatten(cat.children, cat.slug);
    }
  }
  flatten(tree);
  const productCats = flatCats.filter((c) => product.categoryIds?.includes(c.id));

  const netCents = price?.netUnitAmountCents ?? 0;
  const vatRate = price?.vatRate ?? 'general';
  const grossCents = calcGrossPrice(netCents, vatRate);
  const vatPercent = vatRate === 'general' ? 21 : 10;

  return (
    <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      {/* Breadcrumb */}
      <nav className="mb-6" aria-label="Breadcrumb">
        <ol className="flex items-center gap-2 text-sm text-gray-500 flex-wrap">
          <li><Link href="/" className="hover:text-[#70ad47]">Inicio</Link></li>
          <li><span className="text-gray-300">/</span></li>
          <li><Link href="/products" className="hover:text-[#70ad47]">Productos</Link></li>
          {productCats[0] && (
            <>
              <li><span className="text-gray-300">/</span></li>
              <li><Link href={`/categories/${productCats[0].slug}`} className="hover:text-[#70ad47]">{productCats[0].name}</Link></li>
            </>
          )}
          <li><span className="text-gray-300">/</span></li>
          <li className="text-gray-900 font-medium truncate max-w-xs">{product.name}</li>
        </ol>
      </nav>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-12">
        {/* Image */}
        <div>
          {/* Detail image: wrap in a flex container so the inner box is
              horizontally centred inside the grid cell. The inner box has
              `aspect-[5/7] max-h-[500px]` so it always has a real height
              (next/image `fill` needs a non-zero parent) and the image is
              letterboxed with `object-contain`. */}
          <div className="flex justify-center">
            <div className="relative w-full max-w-md aspect-[5/7] max-h-[500px] bg-gray-50 rounded-2xl border border-gray-100 overflow-hidden">
              {product.images?.[0] ? (
                <Image
                  src={product.images[0].url}
                  alt={product.name}
                  fill
                  className="object-contain"
                  priority
                  sizes="(max-width: 1024px) 100vw, 50vw"
                />
              ) : (
                <span className="absolute inset-0 flex items-center justify-center text-8xl">🌿</span>
              )}
            </div>
          </div>
        </div>

        {/* Details */}
        <div>
          {brand && (
            <Link href={`/brands/${brand.slug}`} className="text-sm text-[#E76F51] font-medium uppercase tracking-wide hover:underline">
              {brand.name}
            </Link>
          )}
          <h1 className="text-3xl font-bold text-gray-900 mt-2" style={{ fontFamily: 'var(--font-heading)' }}>
            {product.name}
          </h1>

          <ProductAttributes attributes={product.attributes} />

          {/* Price */}
          {price ? (
            <div className="mt-6 bg-gray-50 rounded-xl p-6">
              <div className="flex items-baseline gap-3">
                <span className="text-4xl font-bold text-[#70ad47]">{formatPrice(grossCents)}</span>
                <span className="text-lg text-gray-500">inc. IVA</span>
              </div>
              <div className="mt-2 text-sm text-gray-500">
                {formatPrice(netCents)} sin IVA · IVA {vatPercent}%
              </div>
            </div>
          ) : (
            <div className="mt-6 bg-gray-50 rounded-xl p-6">
              <span className="text-2xl text-gray-400">Precio no disponible</span>
            </div>
          )}

          {/* Stock */}
          {stock && (
            <div className="mt-4">
              {stock.available ? (
                <div className="flex items-center gap-2 text-[#70ad47]">
                  <svg className="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
                    <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clipRule="evenodd" />
                  </svg>
                  <span className="text-sm font-medium">En stock — {stock.availableQuantity} unidades</span>
                </div>
              ) : (
                <div className="flex items-center gap-2 text-red-500">
                  <svg className="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
                    <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clipRule="evenodd" />
                  </svg>
                  <span className="text-sm font-medium">Sin stock</span>
                </div>
              )}
            </div>
          )}

          {/* Add to cart */}
          {stock?.available && primaryVariant ? (
            <ProductAddToCart
              variantId={primaryVariant.id}
              productId={product.id}
              productName={product.name}
              priceCents={grossCents}
              imageUrl={product.images?.[0]?.url}
              available={true}
              minPurchaseQty={product.minPurchaseQty ?? 1}
            />
          ) : (
            <button
              disabled
              className="mt-6 px-8 py-3.5 bg-gray-200 text-gray-500 font-semibold rounded-xl cursor-not-allowed"
            >
              Agotado
            </button>
          )}

          {/* Description */}
          {product.description && (
            <div className="mt-8">
              <h2 className="text-lg font-semibold text-gray-900 mb-2">Descripción</h2>
              <div
                className="text-gray-600 leading-relaxed rich-text prose prose-sm max-w-none text-justify"
                dangerouslySetInnerHTML={{ __html: formatRichText(product.description) }}
              />
            </div>
          )}

          {/* Disclaimer IA (F-112) */}
          {product.aiAssisted && (
            <aside
              role="note"
              aria-label="Aviso sobre contenido generado por IA"
              className="mt-8 rounded-2xl border border-amber-200 bg-amber-50 p-4 text-sm text-amber-900"
            >
              <p className="font-semibold mb-1">Aviso sobre el contenido de esta ficha</p>
              <p className="mb-2">
                Parte del contenido de esta ficha puede haber sido generado o asistido mediante inteligencia artificial y revisado antes de su publicación.
              </p>
              <p>
                Composición y características pueden cambiar, consultar etiqueta del fabricante.
              </p>
            </aside>
          )}

          {/* Categories */}
          {productCats.length > 0 && (
            <div className="mt-6">
              <h3 className="text-sm font-semibold text-gray-500 uppercase tracking-wide mb-2">Categorías</h3>
              <div className="flex flex-wrap gap-2">
                {productCats.map((cat) => (
                  <Link
                    key={cat.id}
                    href={`/categories/${cat.slug}`}
                    className="px-3 py-1 bg-gray-100 hover:bg-[#70ad47] hover:text-white text-sm rounded-full transition-colors"
                  >
                    {cat.name}
                  </Link>
                ))}
              </div>
            </div>
          )}

          {/* SKU */}
          {primaryVariant && (
            <div className="mt-4 text-xs text-gray-400">
              SKU: {primaryVariant.sku}
              {primaryVariant.ean && ` · EAN: ${primaryVariant.ean}`}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
