import Link from 'next/link';
import Image from 'next/image';
import type { Metadata } from 'next';
import { fetchCategoryBySlug, fetchProducts, fetchBrands } from '@/lib/api';
import { formatRichText } from '@/lib/format-rich-text';

// Category 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 category = await fetchCategoryBySlug(slug);
  if (!category) return { title: 'Categoría no encontrada' };
  return {
    title: category.seoTitle ?? category.name,
    description: category.seoDescription ?? category.description ?? `${category.name} — Productos naturales y orgánicos en mercadodevida.`,
  };
}

function formatPrice(cents: number): string {
  return `€${(cents / 100).toFixed(2)}`;
}

export default async function CategoryPage({ params }: Props) {
  const { slug } = await params;
  const [category, products, brands] = await Promise.all([
    fetchCategoryBySlug(slug),
    fetchProducts({ categorySlug: slug, limit: 20 }),
    fetchBrands(),
  ]);

  if (!category) {
    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">Categoría no encontrada</h1>
        <p className="text-gray-500 mb-8">La categoría que buscas no existe.</p>
        <Link href="/categories" className="text-[#70ad47] font-medium hover:underline">
          Ver todas las categorías →
        </Link>
      </div>
    );
  }

  const breadcrumb = [
    { label: 'Inicio', href: '/' },
    { label: 'Categorías', href: '/categories' },
    { label: category.name, href: `/categories/${category.slug}` },
  ];

  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">
          {breadcrumb.map((item, i) => (
            <li key={item.href} className="flex items-center gap-2">
              {i > 0 && <span className="text-gray-300">/</span>}
              <Link href={item.href} className="hover:text-[#70ad47] transition-colors">
                {item.label}
              </Link>
            </li>
          ))}
        </ol>
      </nav>

      {/* Header */}
      <div className="mb-8">
        <h1 className="text-3xl font-bold text-gray-900" style={{ fontFamily: 'var(--font-heading)' }}>
          {category.name}
        </h1>
        {(category.description || category.seoDescription) && (
          <p className="mt-2 text-gray-600">{category.description || category.seoDescription}</p>
        )}
        <p className="mt-1 text-sm text-gray-500">{products.length} producto{products.length !== 1 ? 's' : ''}</p>
      </div>

      {/* Products grid */}
      {products.length === 0 ? (
        <div className="py-16 text-center">
          <p className="text-gray-500 mb-4">No hay productos en esta categoría todavía.</p>
          <Link href="/categories" className="text-[#70ad47] font-medium hover:underline">
            Explorar otras categorías →
          </Link>
        </div>
      ) : (
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6 justify-items-center">
          {products.map((product) => (
            <Link key={product.id} href={`/products/${product.slug}`} className="group block">
              <div className="bg-gray-50 rounded-xl overflow-hidden border border-gray-100 hover:border-[#70ad47] transition-all hover:shadow-md">
                <div className="relative aspect-square w-full bg-white flex items-center justify-center overflow-hidden">
                  {product.images?.[0] ? (
                    <Image src={product.images[0].url} alt={product.name} fill className="object-contain" sizes="(max-width: 640px) 100vw, (max-width: 1024px) 50vw, 25vw" />
                  ) : (
                    <span className="text-5xl">🌿</span>
                  )}
                </div>
                <div className="p-4">
                  {product.brandId && (
                    <p className="text-xs text-[#E76F51] font-medium uppercase tracking-wide mb-1">
                      {brands.find((b) => b.id === product.brandId)?.name ?? 'Marca'}
                    </p>
                  )}
                  <h3 className="font-semibold text-gray-900 group-hover:text-[#70ad47] transition-colors line-clamp-2 text-sm">
                    {product.name}
                  </h3>
                  {product.description && (
                    <div
                      className="text-gray-500 text-xs mt-1 line-clamp-2 rich-text prose prose-xs max-w-none"
                      dangerouslySetInnerHTML={{ __html: formatRichText(product.description) }}
                    />
                  )}
                  <div className="mt-3 pr-2">
                    <span className="text-lg font-bold text-[#70ad47]">{formatPrice(0)}</span>
                  </div>
                </div>
              </div>
            </Link>
          ))}
        </div>
      )}
    </div>
  );
}
