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

// Search es por-query (searchParams dinámicos), forzamos dinámico: cada
// búsqueda debe ver datos frescos (no se cachea) (F-132).
export const dynamic = 'force-dynamic';

interface Props {
  searchParams: Promise<{ q?: string; brand?: string; category?: string }>;
}

export async function generateMetadata({ searchParams }: Props): Promise<Metadata> {
  const { q } = await searchParams;
  const title = q ? `Buscar: "${q}"` : 'Buscar productos';
  return { title, description: `${title} en mercadodevida.` };
}

export default async function SearchPage({ searchParams }: Props) {
  const { q, brand, category } = await searchParams;
  const query = q?.trim() ?? '';

  const [products, brands, categories] = await Promise.all([
    fetchProducts({ q: query || undefined, brandSlug: brand, categorySlug: category, limit: 24 }),
    fetchBrands(),
    fetchCategories(),
  ]);

  // Flatten categories for display
  const flatCats: Array<{ id: string; name: string; slug: string }> = [];
  function flatten(cats: typeof categories) {
    for (const c of cats) {
      flatCats.push({ id: c.id, name: c.name, slug: c.slug });
      if (c.children?.length) flatten(c.children);
    }
  }
  flatten(categories);

  return (
    <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      {/* Search form */}
      <div className="mb-8">
        <h1 className="text-3xl font-bold text-gray-900 mb-4" style={{ fontFamily: 'var(--font-heading)' }}>
          Buscar productos
        </h1>
        <form method="GET" action="/search" className="flex gap-3">
          <input
            id="search-page-q"
            name="q"
            type="search"
            defaultValue={query}
            placeholder="Buscar productos, marcas, categorías..."
            className="flex-1 px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-[#70ad47] focus:border-transparent outline-none text-gray-900"
            autoFocus
          />
          <button
            type="submit"
            className="px-6 py-3 bg-[#70ad47] hover:bg-[#5a9040] text-white font-semibold rounded-xl transition-colors"
          >
            Buscar
          </button>
        </form>
      </div>

      {/* Results */}
      {query && (
        <div className="mb-6">
          <p className="text-gray-600">
            {products.length > 0
              ? `${products.length} resultado${products.length !== 1 ? 's' : ''} para "${query}"`
              : `Sin resultados para "${query}"`
            }
          </p>
        </div>
      )}

      {products.length === 0 && query ? (
        <div className="py-16 text-center">
          <p className="text-gray-500 text-lg mb-4">No encontramos productos para tu búsqueda.</p>
          <p className="text-gray-400 mb-8">Prueba con otros términos o explora nuestras categorías.</p>
          <div className="flex flex-wrap justify-center gap-2">
            {['Almendras', 'Aceite', 'Vitamina', 'Crema', 'Jabón', 'Matcha'].map((term) => (
              <Link key={term} href={`/search?q=${encodeURIComponent(term)}`}
                className="px-4 py-2 bg-gray-100 hover:bg-[#70ad47] hover:text-white rounded-full text-sm transition-colors">
                {term}
              </Link>
            ))}
          </div>
        </div>
      ) : products.length > 0 ? (
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6 justify-items-center">
          {products.map((product) => {
            const brand_ = brands.find((b) => b.id === product.brandId);
            const cats = product.categoryIds?.map((id) => flatCats.find((c) => c.id === id)).filter(Boolean) ?? [];
            return (
              <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">
                    {brand_ && (
                      <p className="text-xs text-[#E76F51] font-medium uppercase tracking-wide mb-1">{brand_.name}</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 className="py-16 text-center text-gray-500">
          <p>Escribe un término de búsqueda y presiona Enter.</p>
        </div>
      )}
    </div>
  );
}
