import type { Metadata } from "next";
import Link from "next/link";
import { notFound } from "next/navigation";
import { ArrowLeft } from "lucide-react";

import { MarkdownPreview } from "@/components/editor/markdown-preview";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Separator } from "@/components/ui/separator";
import { getAllSlugs, getPost, getRelatedPosts, tagSlug } from "@/lib/blog";
import { articleLd, breadcrumbLd, buildMetadata } from "@/lib/seo";
import { formatDate } from "@/lib/utils";

export const dynamicParams = false;

export function generateStaticParams() {
  return getAllSlugs().map((slug) => ({ slug }));
}

type Params = { params: Promise<{ slug: string }> };

export async function generateMetadata({ params }: Params): Promise<Metadata> {
  const { slug } = await params;
  const post = getPost(slug);
  if (!post) return { title: "Post not found" };

  return buildMetadata({
    title: post.title,
    description: post.description,
    path: `/blog/${post.slug}`,
    type: "article",
    publishedTime: new Date(post.date).toISOString(),
    modifiedTime: post.updated ? new Date(post.updated).toISOString() : undefined,
    keywords: post.tags,
    image: post.cover,
  });
}

export default async function BlogPostPage({ params }: Params) {
  const { slug } = await params;
  const post = getPost(slug);
  if (!post) notFound();
  const related = getRelatedPosts(post, 3);

  return (
    <article className="container max-w-3xl py-12 sm:py-16">
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{
          __html: articleLd({
            title: post.title,
            description: post.description,
            path: `/blog/${post.slug}`,
            image: post.cover,
            datePublished: new Date(post.date).toISOString(),
            dateModified: post.updated ? new Date(post.updated).toISOString() : undefined,
            author: post.author,
          }),
        }}
      />
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{
          __html: breadcrumbLd([
            { name: "Home", url: "/" },
            { name: "Blog", url: "/blog" },
            { name: post.title, url: `/blog/${post.slug}` },
          ]),
        }}
      />

      <nav
        aria-label="Breadcrumb"
        className="flex items-center gap-1 text-xs text-muted-foreground"
      >
        <Link href="/" className="hover:text-foreground">
          Home
        </Link>
        <span aria-hidden>/</span>
        <Link href="/blog" className="hover:text-foreground">
          Blog
        </Link>
        <span aria-hidden>/</span>
        <span className="truncate text-foreground">{post.title}</span>
      </nav>

      <Link
        href="/blog"
        className="mt-3 inline-flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground"
      >
        <ArrowLeft className="h-3.5 w-3.5" /> All posts
      </Link>

      <header className="mt-6">
        <div className="flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
          <time dateTime={post.date}>{formatDate(post.date)}</time>
          {post.updated && post.updated !== post.date ? (
            <>
              <span aria-hidden>·</span>
              <span>updated {formatDate(post.updated)}</span>
            </>
          ) : null}
          <span aria-hidden>·</span>
          <span>{post.readingTime} min read</span>
          {post.tags.map((tag) => (
            <Link key={tag} href={`/blog/tag/${tagSlug(tag)}`}>
              <Badge variant="secondary" className="text-[10px] hover:bg-secondary/80">
                {tag}
              </Badge>
            </Link>
          ))}
        </div>
        <h1 className="mt-3 text-balance text-3xl font-semibold tracking-tight sm:text-4xl">
          {post.title}
        </h1>
        <p className="mt-3 text-lg text-muted-foreground">{post.description}</p>
      </header>

      <Separator className="my-8" />

      <MarkdownPreview source={post.content} />

      <Separator className="my-10" />
      <p className="text-sm text-muted-foreground">
        Written by {post.author}. Found this useful?{" "}
        <Link
          href="/editor"
          className="font-medium text-foreground underline-offset-4 hover:underline"
        >
          Try the editor →
        </Link>
      </p>

      {related.length > 0 ? (
        <section aria-label="Related posts" className="mt-14">
          <h2 className="text-xl font-semibold tracking-tight">Keep reading</h2>
          <p className="mt-1 text-sm text-muted-foreground">
            Hand-picked articles related to this one.
          </p>
          <div className="mt-5 grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
            {related.map((p) => (
              <Link key={p.slug} href={`/blog/${p.slug}`} className="group block">
                <Card className="h-full transition-shadow hover:shadow-md">
                  <CardHeader>
                    <div className="text-[11px] uppercase tracking-wider text-muted-foreground">
                      {formatDate(p.date)} · {p.readingTime} min
                    </div>
                    <CardTitle className="mt-1 text-base group-hover:text-primary">
                      {p.title}
                    </CardTitle>
                    <CardDescription className="line-clamp-3">
                      {p.description}
                    </CardDescription>
                  </CardHeader>
                  <CardContent className="text-xs font-medium text-primary">
                    Read article →
                  </CardContent>
                </Card>
              </Link>
            ))}
          </div>
        </section>
      ) : null}
    </article>
  );
}
