import type { Metadata } from "next";
import Image from "next/image";
import Link from "next/link";
import { notFound } from "next/navigation";

import { RichContent } from "@/components/rich-content";
import { estimateReadTime, formatDate, getAllPosts, getPostBySlug, getPrimaryDescription } from "@/lib/site-data";

export function generateStaticParams() {
  return getAllPosts().map((post) => ({ slug: post.slug }));
}

export function generateMetadata({ params }: { params: { slug: string } }): Metadata {
  const post = getPostBySlug(params.slug);
  if (!post) {
    return {};
  }

  return {
    title: post.seo.rank_math_title || post.title,
    description: post.seo.rank_math_description || getPrimaryDescription(post),
  };
}

export default function BlogPostPage({ params }: { params: { slug: string } }) {
  const post = getPostBySlug(params.slug);

  if (!post) {
    notFound();
  }

  return (
    <article className="page-enter mx-auto flex w-full max-w-4xl flex-col gap-8 pb-10">
      <header className="surface rounded-[2rem] px-6 py-10 sm:px-10 sm:py-12">
        <div className="flex flex-wrap gap-2">
          {(post.terms.category ?? []).map((term) => (
            <Link key={term.id} href={`/category/${term.slug}`} className="rounded-full border border-stone-900/10 px-3 py-1 text-xs font-medium text-stone-700 dark:border-white/10 dark:text-stone-300">{term.name}</Link>
          ))}
        </div>
        <h1 className="mt-5 text-4xl font-semibold tracking-tight text-stone-950 dark:text-white sm:text-5xl">{post.title}</h1>
        <div className="mt-5 flex flex-wrap gap-4 text-sm text-stone-500 dark:text-stone-400">
          <span>{formatDate(post.date)}</span>
          <span>{estimateReadTime(post.content)} min read</span>
          {post.author ? <span>By {post.author.name}</span> : null}
        </div>
        {post.featuredImage ? (
          <div className="relative mt-8 overflow-hidden rounded-[1.75rem]">
            <Image src={post.featuredImage.url} alt={post.featuredImage.alt || post.title} width={1400} height={820} className="h-auto w-full object-cover" priority />
          </div>
        ) : null}
      </header>

      <section className="surface rounded-[2rem] px-6 py-8 sm:px-10 sm:py-10">
        <RichContent html={post.content} />
      </section>
    </article>
  );
}
