import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { getTranslations } from "next-intl/server";
import { MDXRemote } from "next-mdx-remote/rsc";
import { Navbar } from "@/components/layout/navbar";
import { Footer } from "@/components/layout/footer";
import { CommentForm } from "@/components/blog/comment-form";
import { CommentsList } from "@/components/blog/comments-list";
import { JsonLd } from "@/components/seo/json-ld";
import { getPostBySlug, getAllPosts } from "@/lib/blog";
import { ArrowLeft, ArrowRight, Clock, Calendar } from "lucide-react";

export function generateStaticParams({
  params,
}: {
  params: { locale: string };
}) {
  const posts = getAllPosts(params.locale as "fa" | "en");
  return posts.map((p) => ({ slug: p.slug }));
}

const BASE_URL = process.env.NEXT_PUBLIC_SITE_URL ?? "https://meezi.ir";

export async function generateMetadata({
  params,
}: {
  params: Promise<{ locale: string; slug: string }>;
}): Promise<Metadata> {
  const { locale, slug } = await params;
  const post = getPostBySlug(slug, locale as "fa" | "en");
  if (!post) return {};
  const otherLocale = locale === "fa" ? "en" : "fa";
  const otherPost = getPostBySlug(slug, otherLocale as "fa" | "en");
  return {
    title: post.title,
    description: post.excerpt,
    alternates: {
      canonical: `${BASE_URL}/${locale}/blog/${slug}`,
      ...(otherPost ? {
        languages: {
          [locale]: `${BASE_URL}/${locale}/blog/${slug}`,
          [otherLocale]: `${BASE_URL}/${otherLocale}/blog/${slug}`,
        },
      } : {}),
    },
    openGraph: {
      title: post.title,
      description: post.excerpt,
      type: "article",
      publishedTime: post.date,
      url: `${BASE_URL}/${locale}/blog/${slug}`,
    },
  };
}

async function getComments(slug: string) {
  const baseUrl = process.env.MEEZI_API_URL ?? "http://localhost:5001";
  try {
    const res = await fetch(
      `${baseUrl}/api/public/website/posts/${encodeURIComponent(slug)}/comments`,
      { next: { revalidate: 60 } }
    );
    if (!res.ok) return [];
    const json = await res.json();
    // ApiResponse<T> shape: { success, data }; or direct array fallback
    const payload = json?.data ?? json;
    return Array.isArray(payload) ? payload : [];
  } catch {
    return [];
  }
}

export default async function BlogPostPage({
  params,
}: {
  params: Promise<{ locale: string; slug: string }>;
}) {
  const { locale, slug } = await params;
  const t = await getTranslations({ locale, namespace: "blog" });
  const post = getPostBySlug(slug, locale as "fa" | "en");
  if (!post) notFound();

  const isRtl = locale === "fa";
  const Arrow = isRtl ? ArrowRight : ArrowLeft;
  const base = `/${locale}`;

  const comments = await getComments(slug);

  const jsonLdData = {
    headline: post.title,
    description: post.excerpt,
    datePublished: post.date,
    author: { "@type": "Person", name: post.author },
    publisher: { "@type": "Organization", name: "Meezi", url: "https://meezi.ir" },
    inLanguage: locale === "fa" ? "fa-IR" : "en",
  };

  return (
    <>
      <JsonLd type="BlogPosting" locale={locale} data={jsonLdData} />
      <Navbar />
      <main className="pt-16">
        {/* Header */}
        <div className="bg-gradient-to-br from-brand-900 to-brand-700 pb-16 pt-16">
          <div className="mx-auto max-w-3xl px-4 sm:px-6 lg:px-8">
            <span className="mb-4 inline-flex items-center gap-1.5 rounded-full border border-white/20 bg-white/10 px-3 py-1 text-xs font-semibold text-white/80">
              {post.category}
            </span>
            <h1 className="text-3xl font-extrabold leading-tight text-white sm:text-4xl">
              {post.title}
            </h1>
            <div className="mt-5 flex flex-wrap items-center gap-4 text-sm text-white/60">
              <span className="flex items-center gap-1.5">
                <Calendar className="h-4 w-4" />
                {post.date}
              </span>
              <span className="flex items-center gap-1.5">
                <Clock className="h-4 w-4" />
                {post.readingTime}
              </span>
              <span>{post.author}</span>
            </div>
          </div>
        </div>

        {/* Content */}
        <div className="mx-auto max-w-3xl px-4 py-12 sm:px-6 lg:px-8">
          <div className="prose prose-sm sm:prose-base prose-gray max-w-none prose-headings:font-bold prose-headings:text-gray-900 prose-a:text-brand-700 prose-strong:text-gray-900">
            <MDXRemote source={post.content} />
          </div>

          {/* Back link */}
          <div className="mt-12 border-t border-gray-100 pt-8">
            <a
              href={`${base}/blog`}
              className="inline-flex items-center gap-2 text-sm font-semibold text-brand-700 hover:text-brand-800"
            >
              <Arrow className="h-4 w-4" />
              {t("backToBlog")}
            </a>
          </div>

          {/* Comments section */}
          <div className="mt-12 space-y-8">
            <div className="border-t border-gray-100 pt-8">
              <CommentsList comments={comments} locale={locale} />
            </div>
            <CommentForm slug={slug} locale={locale} />
          </div>
        </div>
      </main>
      <Footer />
    </>
  );
}
