import type { Metadata } from "next";
import Link from "next/link";
import { notFound } from "next/navigation";
import { Search, X } from "lucide-react";
import { articleCategories, isLocale, localizedPath, type ArticleCategory } from "@alterra/shared";
import PageHero from "@/components/PageHero";
import ClosingCta from "@/components/ClosingCta";
import ArticleCard from "@/components/insights/ArticleCard";
import { buildCrumbs } from "@/lib/breadcrumbs";
import { fetchArticles } from "@/lib/api";
import { getInsightsCopy } from "@/lib/insightsCopy";
import { fill } from "@/lib/propertyCopy";
import { getLayoutCopy, getPageCopy } from "@/lib/site";
import { pageMetadata } from "@/lib/seo";

type Params = Promise<{ lang: string }>;
type SearchParams = Promise<Record<string, string | string[] | undefined>>;

const PAGE_SIZE = 9;

// Category, search and page come from the query string.
export const dynamic = "force-dynamic";

const first = (value: string | string[] | undefined) => (Array.isArray(value) ? value[0] : value);
const isCategory = (value?: string): value is ArticleCategory => !!value && (articleCategories as readonly string[]).includes(value);

export async function generateMetadata({ params, searchParams }: { params: Params; searchParams: SearchParams }): Promise<Metadata> {
  const { lang } = await params;
  if (!isLocale(lang)) return {};
  const sp = await searchParams;
  const category = first(sp.category);
  const page = getPageCopy(lang, "/insights")!;
  const copy = getInsightsCopy(lang);
  const title = isCategory(category) ? `${copy.categories[category]} · ${page.crumb}` : page.title;
  const meta = pageMetadata({ lang, path: "/insights", title, description: page.description });
  // Categories are indexable; searches and pagination are not part of the canonical URL.
  const suffix = isCategory(category) ? `?category=${category}` : "";
  return {
    ...meta,
    alternates: {
      canonical: `${localizedPath(lang, "/insights")}${suffix}`,
      languages: {
        en: `${localizedPath("en", "/insights")}${suffix}`,
        es: `${localizedPath("es", "/insights")}${suffix}`,
        "x-default": `${localizedPath("en", "/insights")}${suffix}`,
      },
    },
    robots: first(sp.q) ? { index: false } : undefined,
  };
}

export default async function InsightsPage({ params, searchParams }: { params: Params; searchParams: SearchParams }) {
  const { lang } = await params;
  if (!isLocale(lang)) notFound();
  const sp = await searchParams;
  const category = isCategory(first(sp.category)) ? (first(sp.category) as ArticleCategory) : undefined;
  const q = first(sp.q)?.trim().slice(0, 80) || undefined;
  const pageNumber = Math.max(1, Number(first(sp.page)) || 1);

  const page = getPageCopy(lang, "/insights")!;
  const copy = getInsightsCopy(lang);
  const list = await fetchArticles({ lang, category, q, page: pageNumber, pageSize: PAGE_SIZE });

  const base = localizedPath(lang, "/insights");
  const href = (next: { category?: string; q?: string; page?: number }) => {
    const params = new URLSearchParams();
    if (next.category) params.set("category", next.category);
    if (next.q) params.set("q", next.q);
    if (next.page && next.page > 1) params.set("page", String(next.page));
    return params.size ? `${base}?${params}` : base;
  };

  // The newest article is featured on the first, unfiltered page.
  const showFeatured = !category && !q && pageNumber === 1 && (list?.items.length ?? 0) > 1;
  const [featured, ...others] = list?.items ?? [];
  const gridItems = showFeatured ? others : (list?.items ?? []);

  return (
    <main>
      <PageHero lang={lang} eyebrow={page.eyebrow} title={page.title} intro={page.description} crumbs={buildCrumbs(lang, "/insights", page.crumb)} />

      <section className="bg-cream">
        <div className="mx-auto max-w-7xl px-5 py-14 md:px-8 md:py-20">
          {/* Categories + search */}
          <div className="flex flex-col gap-6 border-b border-ink/10 pb-8 lg:flex-row lg:items-center lg:justify-between">
            <nav aria-label={page.crumb} className="flex flex-wrap gap-2">
              {[undefined, ...articleCategories].map((c) => {
                const active = c === category;
                return (
                  <Link
                    key={c ?? "all"}
                    href={href({ category: c, q })}
                    aria-current={active ? "true" : undefined}
                    className={`border px-4 py-2 text-sm transition ${active ? "border-forest bg-forest text-cream" : "border-ink/15 hover:border-ink"}`}
                  >
                    {c ? copy.categories[c] : copy.all}
                  </Link>
                );
              })}
            </nav>
            <form action={base} method="get" role="search" className="flex w-full max-w-sm items-center border-b border-ink/25 focus-within:border-gold">
              {category && <input type="hidden" name="category" value={category} />}
              <Search size={16} strokeWidth={1.4} className="text-stone" />
              <input
                name="q"
                defaultValue={q}
                maxLength={80}
                placeholder={copy.search}
                aria-label={copy.search}
                className="min-w-0 flex-1 bg-transparent px-3 py-2.5 text-ink outline-none placeholder:text-stone"
              />
              {q && (
                <Link href={href({ category })} aria-label={copy.clear} className="p-1 text-stone hover:text-ink">
                  <X size={15} strokeWidth={1.5} />
                </Link>
              )}
              <button type="submit" className="eyebrow px-2 text-[0.6rem] text-gold-ink">
                {copy.searchButton}
              </button>
            </form>
          </div>

          {!list ? (
            <p className="py-20 text-center font-serif text-2xl text-ink/70">{copy.unavailable}</p>
          ) : list.items.length === 0 ? (
            <div className="py-20 text-center">
              <p className="font-serif text-2xl text-ink/70">{copy.empty}</p>
              <Link href={base} className="eyebrow mt-6 inline-block border-b border-gold pb-1 text-ink">
                {copy.clear}
              </Link>
            </div>
          ) : (
            <>
              {(q || category) && (
                <p className="mt-8 font-serif text-lg text-forest" aria-live="polite">
                  {list.total === 1 ? copy.resultOne : fill(copy.results, { n: list.total })}
                </p>
              )}
              {showFeatured && featured && (
                <div className="mt-12 border-b border-ink/10 pb-16">
                  <p className="eyebrow mb-6 text-stone">{copy.featured}</p>
                  <ArticleCard article={featured} lang={lang} copy={copy} large />
                </div>
              )}
              <div className="mt-12 grid gap-x-8 gap-y-14 md:grid-cols-2 lg:grid-cols-3">
                {gridItems.map((article) => (
                  <ArticleCard key={article.slug} article={article} lang={lang} copy={copy} />
                ))}
              </div>
              {list.totalPages > 1 && (
                <nav className="mt-16 flex items-center justify-between border-t border-sand pt-8" aria-label={fill(copy.page, { page: list.page, total: list.totalPages })}>
                  {list.page > 1 ? (
                    <Link href={href({ category, q, page: list.page - 1 })} className="eyebrow hover:text-gold-ink">
                      ← {copy.previous}
                    </Link>
                  ) : (
                    <span />
                  )}
                  <span className="text-sm text-stone">{fill(copy.page, { page: list.page, total: list.totalPages })}</span>
                  {list.page < list.totalPages ? (
                    <Link href={href({ category, q, page: list.page + 1 })} className="eyebrow hover:text-gold-ink">
                      {copy.next} →
                    </Link>
                  ) : (
                    <span />
                  )}
                </nav>
              )}
            </>
          )}
        </div>
      </section>

      <ClosingCta lang={lang} copy={getLayoutCopy(lang)} />
    </main>
  );
}
