import { allBlogPosts } from "content-collections";
import type { Metadata } from "next";
import { getTranslations, setRequestLocale } from "next-intl/server";
import { Suspense } from "react";
import { BlogSearch } from "@/components/blog/blog-search";
import { PageMessagesProvider } from "@/components/page-messages-provider";
import { BreadcrumbSchema } from "@/components/ui/breadcrumb-schema";
import { ItemListSchema } from "@/components/ui/item-list-schema";
import { getPathname } from "@/i18n/navigation";

const BASE_URL = "https://www.elevaseo.com";

interface BlogPageProps {
  params: Promise<{ locale: string }>;
}

export async function generateMetadata({
  params,
}: BlogPageProps): Promise<Metadata> {
  const { locale } = await params;
  const t = await getTranslations({ locale, namespace: "blog" });

  const pathname = getPathname({ locale, href: "/blog" });
  return {
    title: t("metaTitle"),
    description: t("metaDescription"),
    alternates: {
      canonical: pathname,
      languages: {
        fr: getPathname({ locale: "fr", href: "/blog" }),
        en: getPathname({ locale: "en", href: "/blog" }),
        "x-default": getPathname({ locale: "fr", href: "/blog" }),
      },
    },
  };
}

export default async function BlogPage({ params }: BlogPageProps) {
  const { locale } = await params;
  setRequestLocale(locale);

  const t = await getTranslations({ locale, namespace: "blog" });

  const posts = allBlogPosts
    .filter((post) => post.locale === locale && post.published)
    .sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime());

  const categories = [...new Set(posts.map((p) => p.category))].sort();

  const prefix = locale === "fr" ? "" : `/${locale}`;
  const itemListItems = posts.map((post) => ({
    url: `${BASE_URL}${prefix}/blog/${post.categorySlug}/${post.slug}`,
    name: post.title,
  }));

  const serializedPosts = posts.map((p) => ({
    title: p.title,
    description: p.description,
    date: p.date,
    slug: p.slug,
    category: p.category,
    categorySlug: p.categorySlug,
    image: p.image,
    tags: p.tags,
  }));

  return (
    <PageMessagesProvider namespaces={["blog"]}>
      <div className="min-h-screen">
        <BreadcrumbSchema
          items={[{ name: "Home", href: "/" }, { name: "Blog" }]}
          locale={locale}
        />
        <ItemListSchema items={itemListItems} />

        <section className="mx-auto max-w-7xl px-4 py-16 sm:px-6 md:py-24 lg:px-8">
          <div className="mb-12 text-center md:mb-16">
            <h1 className="font-bold text-4xl text-white tracking-tight md:text-5xl">
              {t("title")}
            </h1>
            <p className="mx-auto mt-4 max-w-2xl text-lg text-neutral-300">
              {t("subtitle")}
            </p>
          </div>

          <Suspense>
            <BlogSearch
              categories={categories}
              locale={locale}
              posts={serializedPosts}
            />
          </Suspense>
        </section>
      </div>
    </PageMessagesProvider>
  );
}
