import type { Metadata } from 'next';
import { notFound } from 'next/navigation';
import { ProductCard } from '@/components/product-card';
import { AddToCart } from '@/components/add-to-cart';
import { getProductBySlug, searchProducts } from '@/lib/api';
import { formatRichText } from '@/lib/format-rich-text';
import { absoluteUrl, metadataTitle } from '@/lib/seo';
import { breadcrumbJsonLd, JsonLdScript, productJsonLd } from '@/lib/seo/json-ld';

export const revalidate = 300;

type PageProps = Readonly<{ params: Promise<{ slug: string }> }>;

export function generateStaticParams() {
  return [];
}

async function loadProduct(slug: string) {
  try {
    return await getProductBySlug(slug);
  } catch {
    notFound();
  }
}

export async function generateMetadata({ params }: PageProps): Promise<Metadata> {
  const { slug } = await params;
  const product = await loadProduct(slug);
  const title = product.seoTitle ?? product.name;
  const description = (product.seoDescription ?? product.description ?? `Comprar ${product.name}`).replace(/<[^>]*>/g, ' ').replace(/\s+/g, ' ').trim().slice(0, 300);
  const image = product.images?.find((item) => item.role === 'main') ?? product.images?.[0];

  return {
    title: metadataTitle(title),
    description,
    alternates: { canonical: absoluteUrl(product.url) },
    openGraph: {
      title,
      description,
      url: absoluteUrl(product.url),
      type: 'website',
      images: image ? [{ url: image.url, alt: image.altText }] : undefined,
    },
  };
}

export default async function ProductPage({ params }: PageProps) {
  const { slug } = await params;
  const product = await loadProduct(slug);
  const related = await searchProducts({ limit: 3, offset: 0 }).catch(() => []);
  const image = product.images?.find((item) => item.role === 'main') ?? product.images?.[0];
  const breadcrumbs = breadcrumbJsonLd([
    { name: 'Inicio', path: '/' },
    { name: product.name, path: product.url },
  ]);

  return (
    <div className="mx-auto max-w-6xl px-6 py-12">
      <JsonLdScript data={[productJsonLd(product), breadcrumbs]} />
      <nav className="text-sm text-stone-600" aria-label="Breadcrumb">
        <a href="/" className="hover:text-emerald-800">
          Inicio
        </a>{' '}
        / <span>{product.name}</span>
      </nav>

      <article className="mt-8 grid gap-10 md:grid-cols-[0.9fr_1.1fr] md:items-start">
        <div className="overflow-hidden rounded-[2rem] border border-emerald-900/10 bg-emerald-50">
          {image ? (
            // eslint-disable-next-line @next/next/no-img-element
            <img
              src={image.url}
              alt={image.altText}
              className="block w-full max-h-[600px] object-contain"
            />
          ) : (
            <div className="flex aspect-[4/3] items-center justify-center text-emerald-900">
              Imagen próximamente
            </div>
          )}
        </div>
        <div className="space-y-6">
          <p className="text-sm font-semibold uppercase tracking-[0.25em] text-emerald-700">
            Producto activo
          </p>
          <h1 className="text-4xl font-bold tracking-tight text-emerald-950 md:text-5xl">
            {product.name}
          </h1>
          <div className="text-lg leading-8 text-stone-700">
            {product.description ? (
              <div className="rich-text text-justify" dangerouslySetInnerHTML={{ __html: formatRichText(product.description) }} />
            ) : (
              'Producto del catálogo público de mercadodevida.'
            )}
          </div>
          <dl className="grid gap-4 rounded-3xl border border-emerald-900/10 bg-white p-6 text-sm text-stone-700 sm:grid-cols-2">
            <div>
              <dt className="font-semibold text-emerald-950">URL pública</dt>
              <dd>{product.url}</dd>
            </div>
            <div>
              <dt className="font-semibold text-emerald-950">Estado</dt>
              <dd>{product.state}</dd>
            </div>
          </dl>
          <AddToCart
            productId={product.id}
            productName={product.name}
            unitPriceCents={1000}
            imageUrl={image?.url}
          />
        </div>
      </article>

      {related.length > 0 ? (
        <section className="mt-16">
          <h2 className="text-2xl font-semibold text-emerald-950">También te puede interesar</h2>
          <div className="mt-6 grid gap-5 md:grid-cols-3">
            {related
              .filter((item) => item.slug !== product.slug)
              .map((item) => (
                <ProductCard key={item.id} product={item} />
              ))}
          </div>
        </section>
      ) : null}
    </div>
  );
}
