import Image from "next/image";
import Link from "next/link";
import { notFound } from "next/navigation";
import { Bookmark, Clock, Heart, Share2 } from "lucide-react";
import { ArticleCard } from "@/components/article-card";
import { breadcrumbJsonLd, newsArticleJsonLd, siteMetadata } from "@/lib/seo";
import { getArticleBySlug, getRelatedArticles } from "@/lib/data";
import { prisma } from "@/lib/prisma";

export const dynamic = "force-dynamic";

export async function generateMetadata({ params }: { params: Promise<{ slug: string }> }) {
  const { slug } = await params;
  const article = await getArticleBySlug(slug);
  if (!article) return siteMetadata({ title: "Article", path: `/article/${slug}` });

  return siteMetadata({
    title: article.metaTitle || article.title,
    description: article.metaDescription || article.excerpt,
    image: article.coverImage,
    path: `/article/${article.slug}`,
    type: "article"
  });
}

export default async function ArticlePage({ params }: { params: Promise<{ slug: string }> }) {
  const { slug } = await params;
  const article = await getArticleBySlug(slug);
  if (!article) notFound();

  await prisma.article.update({ where: { id: article.id }, data: { views: { increment: 1 } } });
  const related = await getRelatedArticles(article.categoryId, article.id);

  const jsonLd = [
    newsArticleJsonLd(article),
    breadcrumbJsonLd([
      { name: "Home", path: "/" },
      { name: article.category.name, path: `/category/${article.category.slug}` },
      { name: article.title, path: `/article/${article.slug}` }
    ])
  ];

  return (
    <article className="px-4 py-10 sm:px-6 lg:px-8">
      <script type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }} />
      <div className="mx-auto max-w-5xl">
        <Link href={`/category/${article.category.slug}`} className="font-display text-xs font-bold uppercase tracking-[.28em] text-cyanx">{article.category.name}</Link>
        <h1 className="mt-4 font-display text-4xl font-black leading-tight text-white sm:text-6xl">{article.title}</h1>
        <p className="mt-5 text-lg leading-8 text-white/68">{article.excerpt}</p>
        <div className="mt-6 flex flex-wrap items-center gap-4 text-sm text-white/48">
          <span>By {article.author.name || "Infomix Desk"}</span>
          <span>{article.publishedAt?.toLocaleDateString("en", { dateStyle: "medium" })}</span>
          <span className="flex items-center gap-1"><Clock size={15} /> {article.readingMinutes} min read</span>
        </div>
        <div className="mt-6 flex gap-2">
          <button className="rounded-full border border-white/12 p-3 text-white/72 hover:border-cyanx hover:text-cyanx" aria-label="Like"><Heart size={18} /></button>
          <button className="rounded-full border border-white/12 p-3 text-white/72 hover:border-cyanx hover:text-cyanx" aria-label="Bookmark"><Bookmark size={18} /></button>
          <button className="rounded-full border border-white/12 p-3 text-white/72 hover:border-cyanx hover:text-cyanx" aria-label="Share"><Share2 size={18} /></button>
        </div>
      </div>

      {article.coverImage && (
        <div className="mx-auto mt-8 max-w-6xl">
          <div className="relative aspect-[16/8] overflow-hidden rounded-lg">
            <Image src={article.coverImage} alt={article.coverAlt || article.title} fill priority sizes="100vw" className="object-cover" />
          </div>
        </div>
      )}

      <div className="mx-auto mt-10 grid max-w-6xl gap-8 lg:grid-cols-[1fr_300px]">
        <div className="article-content" dangerouslySetInnerHTML={{ __html: article.content }} />
        <aside className="space-y-4">
          <div className="glass rounded-lg p-5">
            <h2 className="font-display text-lg font-bold text-white">AI summary</h2>
            <p className="mt-3 text-sm leading-6 text-white/62">{article.aiSummary || article.excerpt}</p>
          </div>
          <div className="glass rounded-lg p-5">
            <h2 className="font-display text-lg font-bold text-white">Tags</h2>
            <div className="mt-3 flex flex-wrap gap-2">
              {article.tags.map(({ tag }) => (
                <Link href={`/search?q=${tag.slug}`} key={tag.id} className="rounded-full border border-white/12 px-3 py-1 text-xs text-white/62 hover:border-cyanx hover:text-cyanx">#{tag.name}</Link>
              ))}
            </div>
          </div>
          <div className="rounded-lg border border-dashed border-white/16 p-6 text-center text-xs uppercase tracking-[.2em] text-white/35">AdSense slot</div>
        </aside>
      </div>

      <section className="mx-auto mt-14 max-w-6xl">
        <h2 className="font-display text-2xl font-black text-white">Related articles</h2>
        <div className="mt-6 grid gap-6 md:grid-cols-2 lg:grid-cols-4">
          {related.map((item) => <ArticleCard key={item.id} article={item} />)}
        </div>
      </section>
    </article>
  );
}
