import { BlogHeroCover } from "@/components/blog/blog-hero-cover";
import { getPublicBlogBySlug, resolvePublicMediaUrl } from "@/lib/public-blog";
import type { Metadata } from "next";
import { ArrowLeft, CalendarDays, User } from "lucide-react";
import Link from "next/link";
import { notFound } from "next/navigation";

const SITE_URL = (process.env.NEXT_PUBLIC_SITE_URL || "https://nizamify.com").replace(/\/$/, "");

function stripHtml(value: string) {
  return value.replace(/<[^>]+>/g, " ").replace(/\s+/g, " ").trim();
}

export async function generateMetadata({
  params,
}: {
  params: { slug: string };
}): Promise<Metadata> {
  const blog = await getPublicBlogBySlug(params.slug);
  if (!blog) {
    return {
      title: "Blog Not Found | Nizamify",
      robots: {
        index: false,
        follow: false,
      },
    };
  }

  const description =
    blog.excerpt?.trim() || stripHtml(blog.content).slice(0, 180) || "Read this blog post on Nizamify.";
  const canonical = `/blogs/${blog.slug}`;
  const coverAbsolute = resolvePublicMediaUrl(blog.coverImage);

  return {
    title: `${blog.title} | Nizamify Blog`,
    description,
    keywords: ["Nizamify blog", blog.title, blog.category?.name || "General"],
    alternates: {
      canonical,
    },
    openGraph: {
      title: blog.title,
      description,
      type: "article",
      url: `${SITE_URL}${canonical}`,
      publishedTime: blog.publishedAt || blog.createdAt,
      authors: [blog.createdBy?.firstName || blog.createdBy?.username || "Nizamify"],
      images: coverAbsolute
        ? [
          {
            url: coverAbsolute,
            alt: blog.title,
          },
        ]
        : undefined,
    },
    twitter: {
      card: "summary_large_image",
      title: blog.title,
      description,
      images: coverAbsolute ? [coverAbsolute] : undefined,
    },
  };
}

export default async function BlogDetailPage({ params }: { params: { slug: string } }) {
  const blog = await getPublicBlogBySlug(params.slug);
  if (!blog) notFound();

  const authorName =
    [blog.createdBy?.firstName, blog.createdBy?.lastName].filter(Boolean).join(" ").trim() ||
    blog.createdBy?.username ||
    "Admin";
  const coverSrc = resolvePublicMediaUrl(blog.coverImage);
  const publishedLabel = blog.publishedAt
    ? new Date(blog.publishedAt).toLocaleDateString(undefined, {
      year: "numeric",
      month: "long",
      day: "numeric",
    })
    : null;

  const postSchema = {
    "@context": "https://schema.org",
    "@type": "BlogPosting",
    headline: blog.title,
    description: blog.excerpt || stripHtml(blog.content).slice(0, 180),
    image: coverSrc || undefined,
    datePublished: blog.publishedAt || blog.createdAt,
    dateModified: blog.createdAt || blog.publishedAt,
    articleSection: blog.category?.name || "General",
    author: {
      "@type": "Person",
      name: authorName,
    },
    publisher: {
      "@type": "Organization",
      name: "Nizamify",
      url: SITE_URL,
    },
    mainEntityOfPage: `${SITE_URL}/blogs/${blog.slug}`,
  };
  const breadcrumbSchema = {
    "@context": "https://schema.org",
    "@type": "BreadcrumbList",
    itemListElement: [
      {
        "@type": "ListItem",
        position: 1,
        name: "Home",
        item: `${SITE_URL}/`,
      },
      {
        "@type": "ListItem",
        position: 2,
        name: "Blogs",
        item: `${SITE_URL}/blogs`,
      },
      {
        "@type": "ListItem",
        position: 3,
        name: blog.title,
        item: `${SITE_URL}/blogs/${blog.slug}`,
      },
    ],
  };

  return (
    <div className="min-h-[80vh] bg-gradient-to-b from-[#F8F9FA] via-white to-white">
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: JSON.stringify(postSchema) }}
      />
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: JSON.stringify(breadcrumbSchema) }}
      />

      <div >
        <div className="container max-w-8xl px-4 pt-5 sm:px-6">
          <Link
            href="/blogs"
            className="inline-flex items-center gap-2 text-sm font-semibold text-[#007BFF] transition-colors hover:text-[#003D6B]"
          >
            <ArrowLeft className="size-4 shrink-0" aria-hidden />
            Back to blog
          </Link>
        </div>
      </div>

      <div className="container max-w-8xl px-4 pb-20 pt-10 sm:px-6 sm:pt-12">
        <header className="text-center sm:text-left">
          <p className="mb-4 inline-flex rounded-full border border-[#007BFF]/30 bg-[#007BFF]/5 px-3 py-1 text-xs font-bold uppercase tracking-wider text-[#003D6B]">
            {blog.category?.name || "General"}
          </p>
          <h1 className="text-balance text-3xl font-bold leading-tight tracking-tight text-[#003D6B] sm:text-4xl md:text-[2.75rem] md:leading-[1.15]">
            {blog.title}
          </h1>
          <div className="mt-6 flex flex-wrap items-center justify-center gap-x-6 gap-y-2 text-sm text-slate-600 sm:justify-start">
            <span className="inline-flex items-center gap-2">
              <span className="flex size-8 items-center justify-center rounded-full bg-[#003D6B]/10 text-[#003D6B]">
                <User className="size-4" aria-hidden />
              </span>
              <span className="font-medium text-slate-800">{authorName}</span>
            </span>
            {publishedLabel ? (
              <span className="inline-flex items-center gap-2 text-slate-500">
                <CalendarDays className="size-4 shrink-0 text-[#007BFF]" aria-hidden />
                <time dateTime={blog.publishedAt}>{publishedLabel}</time>
              </span>
            ) : null}
          </div>
        </header>

        {coverSrc ? (
          <div className="mt-10">
            <BlogHeroCover src={coverSrc} alt={blog.title} />
          </div>
        ) : null}

        <article
          className="mt-5"
          dangerouslySetInnerHTML={{ __html: blog.content }}
        />

        <div className="mt-12 flex justify-center border-t border-slate-100 pt-10 sm:justify-start">
          <Link
            href="/blogs"
            className="inline-flex items-center gap-2 rounded-full border-2 border-[#007BFF]/35 bg-white px-5 py-2.5 text-sm font-semibold text-[#003D6B] shadow-sm transition-colors hover:border-[#007BFF]/60 hover:bg-slate-50"
          >
            <ArrowLeft className="size-4" aria-hidden />
            More articles
          </Link>
        </div>
      </div>
    </div>
  );
}
