import type { Metadata } from "next";
import Image from "next/image";
import { notFound } from "next/navigation";
import { prisma } from "@/lib/prisma";
import { formatDate, siteUrl } from "@/lib/utils";

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

function seoKeywords(value?: string | null) {
  return value?.split(",").map((keyword) => keyword.trim()).filter(Boolean);
}

export async function generateMetadata({ params }: PageProps): Promise<Metadata> {
  const { slug } = await params;
  const post = await prisma.post.findUnique({ where: { slug } });

  if (!post) {
    return {};
  }

  return {
    title: post.seoTitle ?? post.title,
    description: post.seoDescription ?? post.excerpt,
    keywords: seoKeywords(post.seoKeywords),
    alternates: { canonical: siteUrl(`/articles/${post.slug}`) },
    openGraph: {
      title: post.seoTitle ?? post.title,
      description: post.seoDescription ?? post.excerpt,
      images: post.coverImage ? [{ url: post.coverImage, alt: post.title }] : undefined,
      url: siteUrl(`/articles/${post.slug}`),
      type: "article"
    },
    twitter: {
      card: post.coverImage ? "summary_large_image" : "summary",
      title: post.seoTitle ?? post.title,
      description: post.seoDescription ?? post.excerpt,
      images: post.coverImage ? [post.coverImage] : undefined
    }
  };
}

export default async function ArticleDetailPage({ params }: PageProps) {
  const { slug } = await params;
  const post = await prisma.post.findUnique({
    where: { slug },
    include: { category: true }
  });

  if (!post || post.status !== "PUBLISHED" || post.approvalStatus !== "APPROVED") {
    notFound();
  }

  return (
    <main className="container" style={{ padding: "4rem 1.25rem" }}>
      <article className="card" style={{ margin: "0 auto", maxWidth: "850px", padding: "2rem" }}>
        <script
          dangerouslySetInnerHTML={{
            __html: JSON.stringify({
              "@context": "https://schema.org",
              "@type": "Article",
              author: { "@type": "Organization", name: "Just Chill Nepal" },
              dateModified: post.updatedAt.toISOString(),
              datePublished: post.publishedAt?.toISOString(),
              description: post.seoDescription ?? post.excerpt,
              headline: post.seoTitle ?? post.title,
              image: post.coverImage ? [siteUrl(post.coverImage)] : undefined,
              mainEntityOfPage: siteUrl(`/articles/${post.slug}`)
            })
          }}
          type="application/ld+json"
        />
        {post.category ? <span className="pill">{post.category.name}</span> : null}
        <h1 style={{ fontSize: "clamp(2.2rem, 5vw, 4.5rem)" }}>{post.title}</h1>
        <p className="muted">{formatDate(post.publishedAt)}</p>
        {post.coverImage ? (
          <div className="article-cover-image">
            <Image alt={post.title} fill priority sizes="(max-width: 900px) 100vw, 850px" src={post.coverImage} unoptimized />
          </div>
        ) : null}
        <p style={{ color: "#fed7aa", fontSize: "1.2rem" }}>{post.excerpt}</p>
        <div style={{ lineHeight: 1.9, whiteSpace: "pre-wrap" }}>{post.content}</div>
      </article>
    </main>
  );
}
