import type { Metadata } from "next";
import Link from "next/link";
import { getNewsroomList } from "@/api/newsroom";
import { PageContainer } from "@/components/layout/PageContainer";
import { SiteFooter } from "@/components/layout/SiteFooter";
import { ArchivesPagination } from "@/components/archives/ArchivesPagination";
import { NewsroomHeader } from "@/components/newsroom/NewsroomHeader";
import { ARCHIVE_YEARS } from "@/components/newsroom/NewsroomArchives";
import { ROUTES } from "@/lib/routes";
import { cn } from "@/lib/cn";
import { env } from "@/config/env";

interface ArchivesPageProps {
  searchParams?: Promise<{ yr?: string; pg?: string }>;
}

export const instant = false;

export async function generateMetadata(
  props: ArchivesPageProps
): Promise<Metadata> {
  const searchParams = await props.searchParams;
  const year = searchParams?.yr || "2026";

  return {
    title: `Archives for ${year} | Sterling Protection Partners`,
    description: `Explore published newsroom articles, intelligence insights, and official announcements for ${year}.`,
    alternates: {
      canonical: `/archives?yr=${year}`,
    },
    openGraph: {
      title: `Archives for ${year} | Sterling Protection Partners`,
      description: `Explore published newsroom articles, intelligence insights, and official announcements for ${year}.`,
      type: "website",
      url: `/archives?yr=${year}`,
    },
    twitter: {
      card: "summary_large_image",
      title: `Archives for ${year} | Sterling Protection Partners`,
      description: `Explore published newsroom articles, intelligence insights, and official announcements for ${year}.`,
    },
  };
}

export default async function ArchivesPage(props: ArchivesPageProps) {
  const searchParams = await props.searchParams;
  const year = searchParams?.yr || "2026";
  const page = Math.max(1, Number(searchParams?.pg) || 1);
  const limit = 40;

  // Fetch archives with yr parameter and limit 40
  const { pagination, archiveYears } = await getNewsroomList({
    page,
    limit,
    year,
  });

  const yearsList =
    archiveYears && archiveYears.length > 0 ? archiveYears : ARCHIVE_YEARS;

  const docs = pagination.docs || [];

  // Schema.org Structured Data (JSON-LD)
  const archiveSchema = {
    "@context": "https://schema.org",
    "@type": "CollectionPage",
    name: `Archives for ${year} | Sterling Protection Partners`,
    url: `${env.siteUrl}/archives?yr=${year}`,
    description: `Explore newsroom archives for ${year}.`,
    mainEntity: {
      "@type": "ItemList",
      itemListElement: docs.map((item, index) => ({
        "@type": "ListItem",
        position: index + 1,
        name: item.t,
        url: `${env.siteUrl}/newsroom/${item.sl || item._id}`,
      })),
    },
  };

  const breadcrumbSchema = {
    "@context": "https://schema.org",
    "@type": "BreadcrumbList",
    itemListElement: [
      {
        "@type": "ListItem",
        position: 1,
        name: "Home",
        item: `${env.siteUrl}/`,
      },
      {
        "@type": "ListItem",
        position: 2,
        name: "Newsroom",
        item: `${env.siteUrl}/newsroom`,
      },
      {
        "@type": "ListItem",
        position: 3,
        name: `Archives for ${year}`,
        item: `${env.siteUrl}/archives?yr=${year}`,
      },
    ],
  };

  return (
    <PageContainer>
      {/* Schema.org Structured Data */}
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: JSON.stringify(archiveSchema) }}
      />
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: JSON.stringify(breadcrumbSchema) }}
      />

      <NewsroomHeader />

      <main className="w-full pt-4 pb-16 sm:pt-6 sm:pb-24">
        <div className="mx-auto w-full max-w-[1280px] px-5 sm:px-8 md:px-[60px]">
          {/* Breadcrumb Navigation */}
          <nav
            aria-label="Breadcrumbs"
            className="mb-6 flex items-center gap-2 text-xs font-medium text-gray-500 sm:text-sm"
          >
            <Link
              href={ROUTES.home}
              className="transition-colors hover:text-accent"
            >
              Home
            </Link>
            <span className="text-gray-400">/</span>
            <Link
              href={ROUTES.newsroom}
              className="transition-colors hover:text-accent"
            >
              Newsroom
            </Link>
            <span className="text-gray-400">/</span>
            <span className="font-semibold text-gray-900">Archives</span>
          </nav>

          {/* Heading Section: Blue Square Icon + "ARCHIVES FOR <year>" */}
          <div className="mb-2 flex items-center gap-2.5">
            <span
              className="inline-block size-4 shrink-0 rounded-[1px] bg-[#0088cc]"
              aria-hidden="true"
            />
            <h1 className="text-xl font-extrabold tracking-tight text-[#0d2440] uppercase sm:text-2xl md:text-[26px]">
              ARCHIVES FOR {year}
            </h1>
          </div>

          {/* Year Filter Switcher */}
          <div className="mt-3 mb-8 flex flex-wrap items-center gap-2 border-b border-[#e5e7eb] pb-5">
            <span className="mr-1 text-xs font-semibold uppercase tracking-wider text-gray-500 sm:text-[13px]">
              Select Year:
            </span>
            {yearsList.map((y) => {
              const yStr = String(y);
              const isActive = yStr === String(year);
              return (
                <Link
                  key={yStr}
                  href={ROUTES.archives(y, 1)}
                  className={cn(
                    "inline-flex items-center justify-center rounded-[3px] px-3.5 py-1 text-xs font-semibold shadow-[0_1px_2px_rgba(0,0,0,0.04)] transition-all sm:text-xs",
                    isActive
                      ? "bg-[#0d2440] text-white"
                      : "border border-gray-300 bg-white text-gray-700 hover:border-accent hover:text-accent hover:bg-slate-50"
                  )}
                >
                  {y}
                </Link>
              );
            })}
          </div>

          {/* 2-Column Headline Grid with single map and bottom borders */}
          {docs.length > 0 ? (
            <div className="grid grid-cols-1 gap-x-10 lg:gap-x-16 md:grid-cols-2">
              {docs.map((item) => {
                const articleLink = item.sl
                  ? ROUTES.newsroomArticle(item.sl)
                  : ROUTES.newsroomArticle(item._id);

                return (
                  <article
                    key={item._id}
                    className="border-b border-[#e5e7eb] py-3 sm:py-3.5"
                  >
                    <Link
                      href={articleLink}
                      title={item.t}
                      className="line-clamp-2 text-[14.5px] font-normal leading-snug text-[#0f172a] transition-colors hover:text-accent sm:text-[15px]"
                    >
                      {item.t}
                    </Link>
                  </article>
                );
              })}
            </div>
          ) : (
            <div className="flex flex-col items-center justify-center rounded-2xl border border-dashed border-gray-200 bg-gray-50/50 py-20 text-center">
              <p className="text-base font-semibold text-gray-700">
                No archived articles found for {year}.
              </p>
              <p className="mt-1 text-sm text-gray-500">
                Select another year or check back later.
              </p>
            </div>
          )}

          {/* Pagination UI */}
          <ArchivesPagination
            currentPage={pagination.page}
            totalPages={pagination.totalPages}
            year={year}
          />
        </div>
      </main>

      <SiteFooter />
    </PageContainer>
  );
}
