import type { Metadata } from "next";
import { notFound } from "next/navigation";
import Image from "next/image";
import { getTranslations } from "next-intl/server";
import { ArrowRight, ArrowLeft, Clock } from "lucide-react";
import { Link } from "@/lib/i18n/navigation";
import { getPostBySlug, getRelatedPosts, estimateReadTime } from "@/lib/db/posts";
import { TiptapRenderer } from "@/components/writing/TiptapRenderer";
import { ReadingProgress } from "@/components/writing/ReadingProgress";
import { ShareButtons } from "@/components/writing/ShareButtons";
import { PostCard } from "@/components/writing/PostCard";
import { Badge } from "@/components/ui/badge";
import { formatDate } from "@/lib/types";

interface Props {
  params: Promise<{ locale: string; slug: string }>;
}

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { slug } = await params;
  const post = await getPostBySlug(slug);
  if (!post) return {};
  return {
    title: post.seoTitle ?? post.title,
    description: post.seoDesc ?? post.excerpt ?? undefined,
    openGraph: {
      title: post.seoTitle ?? post.title,
      description: post.seoDesc ?? post.excerpt ?? undefined,
      images: post.coverImage ? [{ url: post.coverImage }] : [],
    },
  };
}

export const dynamic = "force-dynamic";

export default async function PostPage({ params }: Props) {
  const { locale, slug } = await params;
  const [post, t, tCommon, tCat] = await Promise.all([
    getPostBySlug(slug),
    getTranslations({ locale, namespace: "writing" }),
    getTranslations({ locale, namespace: "common" }),
    getTranslations({ locale, namespace: "writing.categories" }),
  ]);

  if (!post) notFound();

  const related = await getRelatedPosts(locale, post.category, slug);
  const readTime = post.body ? estimateReadTime(post.body) : null;
  const postUrl = `https://biztaghavi.com/${locale}/writing/${slug}`;
  const isRtl = locale === "fa";
  const BackArrow = isRtl ? ArrowRight : ArrowLeft;

  // Flatten tags
  const tags = post.tags.map((pt) => pt.tag);
  const flatRelated = related.map((p) => ({ ...p, tags: p.tags.map((pt) => pt.tag) }));

  return (
    <>
      <ReadingProgress />

      <article className="relative z-10 pt-24">
        {/* Back link */}
        <div className="mx-auto max-w-4xl px-6 py-4">
          <Link
            href="/writing"
            className="inline-flex items-center gap-2 text-sm text-text-secondary hover:text-accent transition-colors"
          >
            <BackArrow size={14} />
            {tCommon("back")}
          </Link>
        </div>

        {/* Header */}
        <header className="mx-auto max-w-4xl px-6 pb-8">
          <div className="mb-4 flex flex-wrap items-center gap-3">
            <Badge>{tCat(post.category)}</Badge>
            <span className="font-mono text-xs text-text-secondary">
              {formatDate(post.publishedAt, locale)}
            </span>
            {readTime && (
              <span className="flex items-center gap-1 font-mono text-xs text-text-secondary">
                <Clock size={12} />
                {readTime} {tCommon("min_read")}
              </span>
            )}
          </div>

          <h1 className="mb-4 text-3xl font-bold leading-tight text-text-primary md:text-4xl lg:text-5xl">
            {post.title}
          </h1>

          {post.excerpt && (
            <p className="text-lg text-text-secondary leading-relaxed">{post.excerpt}</p>
          )}

          <div className="mt-6 flex items-center justify-end gap-4">
            <ShareButtons title={post.title} url={postUrl} />
          </div>
        </header>

        {/* Cover image */}
        {post.coverImage && (
          <div className="relative mb-12 h-64 w-full overflow-hidden md:h-96">
            <Image
              src={post.coverImage}
              alt={post.title}
              fill
              className="object-cover"
              priority
            />
            <div className="absolute inset-0 bg-linear-to-b from-transparent to-background/80" />
          </div>
        )}

        {/* Body */}
        <div className="mx-auto max-w-3xl px-6 pb-16">
          {post.body && <TiptapRenderer html={post.body} />}

          {/* Tags */}
          {tags.length > 0 && (
            <div className="mt-10 flex flex-wrap gap-2 border-t border-border pt-6">
              {tags.map((tag) => (
                <Badge key={tag.id} variant="secondary">{tag.title}</Badge>
              ))}
            </div>
          )}

          {/* Bottom share */}
          <div className="mt-8 flex justify-end">
            <ShareButtons title={post.title} url={postUrl} />
          </div>
        </div>

        {/* Related posts */}
        {flatRelated.length > 0 && (
          <section className="border-t border-border bg-surface/30 px-6 py-16">
            <div className="mx-auto max-w-6xl">
              <h2 className="mb-8 font-mono text-xs text-accent">// {tCommon("related_posts")}</h2>
              <div className="grid gap-5 sm:grid-cols-2 lg:grid-cols-3">
                {flatRelated.map((p) => (
                  <PostCard key={p.id} post={p} categoryLabel={tCat(p.category)} />
                ))}
              </div>
            </div>
          </section>
        )}
      </article>
    </>
  );
}
