import { Metadata } from "next";
import { notFound } from "next/navigation";
import { UI } from "@/lib/config";
import { getPaginatedPosts } from "@/lib/blog";
import PostList from "@/components/blog/PostList";

export const revalidate = 3600; // Revalidate every hour

type Props = {
  params: { lang: "ar" | "en"; page: string };
};

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { lang, page } = params;
  const t = UI[lang].t;
  const pageNumber = parseInt(page, 10);

  if (isNaN(pageNumber) || pageNumber < 1) {
    return {
      title: "Page Not Found",
    };
  }

  const { totalPages } = await getPaginatedPosts(lang, pageNumber, 9);

  if (pageNumber > totalPages) {
    return {
      title: "Page Not Found",
    };
  }

  return {
    title: `${t.blogTitle} - ${t.page} ${pageNumber}`,
    description: t.blogSubtitle,
    alternates: {
      canonical: `/${lang}/blog/page/${pageNumber}`,
      languages: {
        ar: `/ar/blog/page/${pageNumber}`,
        en: `/en/blog/page/${pageNumber}`,
      },
    },
  };
}

export async function generateStaticParams() {
  const arPosts = await getPaginatedPosts("ar", 1, 9);
  const enPosts = await getPaginatedPosts("en", 1, 9);

  const arPages = Array.from({ length: arPosts.totalPages }, (_, i) => ({
    lang: "ar" as const,
    page: (i + 1).toString(),
  }));

  const enPages = Array.from({ length: enPosts.totalPages }, (_, i) => ({
    lang: "en" as const,
    page: (i + 1).toString(),
  }));

  return [...arPages, ...enPages];
}

export default async function BlogPageNumber({ params }: Props) {
  const { lang, page } = params;
  const t = UI[lang].t;
  const dir = UI[lang].dir;

  const pageNumber = parseInt(page, 10);

  // Validate page number
  if (isNaN(pageNumber) || pageNumber < 1) {
    notFound();
  }

  const { posts, currentPage, totalPages } = await getPaginatedPosts(
    lang,
    pageNumber,
    9,
  );

  // Redirect to 404 if page number exceeds total pages
  if (pageNumber > totalPages) {
    notFound();
  }

  return (
    <main className="min-h-screen" dir={dir}>
      {/* Hero Section */}
      <section className="bg-gradient-to-b from-brand-sand/20 to-white dark:from-gray-900 dark:to-gray-950 py-16">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 text-center">
          <h1 className="text-4xl md:text-5xl font-bold text-brand-ink dark:text-white mb-4">
            {t.blogTitle}
          </h1>
          <p className="text-xl text-gray-600 dark:text-gray-300 max-w-3xl mx-auto">
            {t.blogSubtitle}
          </p>
        </div>
      </section>

      {/* Blog Posts */}
      <section className="py-16">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <PostList
            posts={posts}
            lang={lang}
            currentPage={currentPage}
            totalPages={totalPages}
          />
        </div>
      </section>
    </main>
  );
}
