import type { Metadata } from 'next';
import { ProductCard } from '@/components/product-card';
import { searchProducts } from '@/lib/api';
import { absoluteUrl, metadataTitle } from '@/lib/seo';

export const revalidate = 120;

type SearchParams = Record<string, string | string[] | undefined>;
type PageProps = Readonly<{ searchParams: Promise<SearchParams> }>;

function firstParam(value: string | string[] | undefined): string | undefined {
  return Array.isArray(value) ? value[0] : value;
}

function boundedText(value: string | undefined, maxLength = 200): string | undefined {
  const trimmed = value?.trim();
  if (!trimmed) return undefined;
  return trimmed.slice(0, maxLength);
}

function boundedInt(value: string | undefined, fallback: number, min: number, max: number): number {
  const parsed = Number(value);
  if (!Number.isInteger(parsed)) return fallback;
  return Math.min(Math.max(parsed, min), max);
}

export async function generateMetadata({ searchParams }: PageProps): Promise<Metadata> {
  const params = await searchParams;
  const q = boundedText(firstParam(params.q));
  const title = q ? `Resultados para ${q}` : 'Buscar productos';
  const description = q
    ? `Resultados de búsqueda para ${q} en mercadodevida.`
    : 'Buscá productos ecológicos y saludables en mercadodevida.';

  return {
    title: metadataTitle(title),
    description,
    alternates: { canonical: absoluteUrl('/products/search') },
    openGraph: {
      title,
      description,
      url: absoluteUrl('/products/search'),
      type: 'website',
    },
  };
}

export default async function SearchPage({ searchParams }: PageProps) {
  const params = await searchParams;
  const q = boundedText(firstParam(params.q));
  const brandSlug = boundedText(firstParam(params.brandSlug));
  const categorySlug = boundedText(firstParam(params.categorySlug));
  const limit = boundedInt(firstParam(params.limit), 24, 1, 100);
  const offset = boundedInt(firstParam(params.offset), 0, 0, 10_000);
  const products = await searchProducts({ q, brandSlug, categorySlug, limit, offset }).catch(
    () => [],
  );

  return (
    <div className="mx-auto max-w-6xl px-6 py-12">
      <header className="max-w-3xl space-y-4">
        <p className="text-sm font-semibold uppercase tracking-[0.25em] text-emerald-700">
          Búsqueda
        </p>
        <h1 className="text-4xl font-bold tracking-tight text-emerald-950 md:text-5xl">
          {q ? `Resultados para “${q}”` : 'Buscar productos'}
        </h1>
        <p className="text-lg leading-8 text-stone-700">
          Resultados desde la API pública del catálogo, con orden estable y paginación.
        </p>
      </header>

      <section className="mt-10" aria-label="Resultados de búsqueda">
        {products.length > 0 ? (
          <div className="grid gap-5 md:grid-cols-3">
            {products.map((product) => (
              <ProductCard key={product.id} product={product} />
            ))}
          </div>
        ) : (
          <div className="rounded-3xl bg-emerald-50 p-6 text-emerald-950">
            No encontramos productos con esos filtros por ahora.
          </div>
        )}
      </section>
    </div>
  );
}
