import { formatDateMDY } from "@/app/lib/dateFormat";
import type { Metadata } from "next";
import { notFound } from "next/navigation";

import Link from "@/app/components/LocaleLink";
import { getBlogBySlug, getLatestBlogs, getRelatedBlogs } from "@/app/lib/blogs";
import { getBlogImageUrl } from "@/app/lib/image-url";

// Rendered per request from the `blogs` table: a blog added or edited in the
// admin panel is live immediately.
export const dynamic = "force-dynamic";

type Params = { params: Promise<{ slug: string }> };

function stripHtml(html: string | null | undefined): string {
  return (html ?? "").replace(/<[^>]*>/g, " ").replace(/\s+/g, " ").trim();
}

function formatDate(date: string | Date | null): string {
  if (!date) return "";

  return formatDateMDY(new Date(date));
}

export async function generateMetadata({ params }: Params): Promise<Metadata> {
  const { slug } = await params;
  const blog = await getBlogBySlug(slug);

  if (!blog) return {};

  const description =
    blog.metaDescription || blog.excerpt || stripHtml(blog.description).slice(0, 160);

  return {
    title: blog.metaTitle || blog.title,
    description: description || undefined,
    openGraph: {
      title: blog.metaTitle || blog.title,
      description: description || undefined,
      type: "article",
      images: blog.blogImage ? [getBlogImageUrl(blog.blogImage)] : undefined,
    },
  };
}

export default async function BlogDetailPage({ params }: Params) {
  const { slug } = await params;
  const blog = await getBlogBySlug(slug);

  if (!blog) notFound();

  const related = await getRelatedBlogs(blog, 4);
  const recent = (await getLatestBlogs(6)).filter((item) => item.id !== blog.id).slice(0, 5);
  const tags = (blog.tags ?? "")
    .split(",")
    .map((tag) => tag.trim())
    .filter(Boolean);

  return (
    <main className="blog-detail-page">
      <div className="container">
        <nav className="blog-detail-crumb" aria-label="Breadcrumb">
          <Link href="/">Home</Link>
          <span>›</span>
          <Link href="/blogs">Blogs</Link>
          <span>›</span>
          <strong>{blog.title}</strong>
        </nav>

        <div className="row g-4">
          <article className="col-lg-8">
            <header className="blog-detail-head">
              {blog.categoryName && (
                <span className="blog-detail-category">{blog.categoryName}</span>
              )}

              <h1>{blog.title}</h1>

              <div className="blog-detail-meta">
                <span>By {blog.author || "Admin"}</span>
                {blog.postedOn && <span>{formatDate(blog.postedOn)}</span>}
              </div>
            </header>

            {blog.blogImage && (
              // eslint-disable-next-line @next/next/no-img-element
              <img
                src={getBlogImageUrl(blog.blogImage)}
                alt={blog.title}
                className="blog-detail-cover"
              />
            )}

            {/* Trusted: authored by admins in this project's own database. */}
            <div
              className="blog-detail-content"
              dangerouslySetInnerHTML={{ __html: blog.description ?? "" }}
            />

            {tags.length > 0 && (
              <div className="blog-detail-tags">
                {tags.map((tag) => (
                  <span key={tag}>#{tag}</span>
                ))}
              </div>
            )}

            <Link href="/blogs" className="blog-detail-back">
              ← Back to all blogs
            </Link>
          </article>

          <aside className="col-lg-4">
            <div className="blog-detail-side">
              <h2>Recent Blogs</h2>

              {recent.map((item) => (
                <Link
                  key={item.id}
                  href={`/blogs/${item.slug || item.id}`}
                  className="blog-detail-recent"
                >
                  {/* eslint-disable-next-line @next/next/no-img-element */}
                  <img
                    src={getBlogImageUrl(item.previewImage || item.blogImage)}
                    alt=""
                    loading="lazy"
                  />

                  <span>
                    <strong>{item.title}</strong>
                    <small>{formatDate(item.postedOn)}</small>
                  </span>
                </Link>
              ))}
            </div>
          </aside>

        </div>

        {related.length > 0 && (
          <section className="blog-related">
            <h2>Related Blogs</h2>

            <div className="row g-4">
              {related.map((item) => (
                <div className="col-lg-3 col-md-6" key={item.id}>
                  <Link href={`/blogs/${item.slug || item.id}`} className="blog-related-card">
                    {/* eslint-disable-next-line @next/next/no-img-element */}
                    <img
                      src={getBlogImageUrl(item.previewImage || item.blogImage)}
                      alt={item.title}
                      loading="lazy"
                    />

                    <strong>{item.title}</strong>

                    <span className="blog-related-meta">{formatDate(item.postedOn)}</span>
                  </Link>
                </div>
              ))}
            </div>
          </section>
        )}
      </div>
    </main>
  );
}
