import type { Metadata } from "next";
import { notFound } from "next/navigation";
import Image from "next/image";
import Link from "next/link";
import { Clock, Eye, ChevronRight, Tag, ArrowLeft } from "lucide-react";
import type { NewsArticle } from "@/lib/types";

const API_URL = process.env.NEXT_PUBLIC_API_URL ?? "http://localhost:8000";
const BASE_URL = process.env.NEXT_PUBLIC_SITE_URL ?? "https://drivehub.in";

async function getArticle(slug: string): Promise<NewsArticle | null> {
  try {
    const res = await fetch(`${API_URL}/api/news/${slug}`, {
      next: { revalidate: 3600 },
    });
    if (!res.ok) return null;
    return res.json();
  } catch {
    return null;
  }
}

async function getRelatedNews(slug: string): Promise<NewsArticle[]> {
  try {
    const res = await fetch(`${API_URL}/api/news?limit=4`, {
      next: { revalidate: 3600 },
    });
    if (!res.ok) return [];
    const data = await res.json();
    return (data.articles ?? []).filter((a: NewsArticle) => a.slug !== slug).slice(0, 3);
  } catch {
    return [];
  }
}

// ── Dynamic metadata ────────────────────────────────────────────────────────

export async function generateMetadata(
  { params }: { params: Promise<{ slug: string }> }
): Promise<Metadata> {
  const { slug } = await params;
  const article = await getArticle(slug);
  if (!article) return { title: "Article Not Found — DriveHub News" };

  return {
    title: `${article.title} — DriveHub News`,
    description: article.summary,
    openGraph: {
      title: article.title,
      description: article.summary,
      images: article.imageUrl ? [article.imageUrl] : [],
      type: "article",
      publishedTime: article.publishedAt,
      authors: [article.author],
      tags: article.tags,
    },
    twitter: {
      card: "summary_large_image",
      title: article.title,
      description: article.summary,
      images: article.imageUrl ? [article.imageUrl] : [],
    },
    alternates: {
      canonical: `${BASE_URL}/news/${article.slug}`,
    },
  };
}

// ── JSON-LD structured data ─────────────────────────────────────────────────

function ArticleJsonLD({ article }: { article: NewsArticle }) {
  const schema = {
    "@context": "https://schema.org",
    "@type": "NewsArticle",
    headline: article.title,
    description: article.summary,
    image: article.imageUrl ?? undefined,
    datePublished: article.publishedAt,
    author: {
      "@type": "Organization",
      name: article.author,
    },
    publisher: {
      "@type": "Organization",
      name: "DriveHub",
      logo: {
        "@type": "ImageObject",
        url: `${BASE_URL}/favicon.ico`,
      },
    },
    mainEntityOfPage: {
      "@type": "WebPage",
      "@id": `${BASE_URL}/news/${article.slug}`,
    },
  };

  return (
    <script
      type="application/ld+json"
      dangerouslySetInnerHTML={{ __html: JSON.stringify(schema) }}
    />
  );
}

// ── Category badge color ────────────────────────────────────────────────────

const CATEGORY_COLORS: Record<string, string> = {
  Launch:     "bg-blue-50 text-blue-700 border-blue-200",
  Facelift:   "bg-violet-50 text-violet-700 border-violet-200",
  EV:         "bg-emerald-50 text-emerald-700 border-emerald-200",
  Industry:   "bg-amber-50 text-amber-700 border-amber-200",
  Review:     "bg-orange-50 text-orange-700 border-orange-200",
  Comparison: "bg-rose-50 text-rose-700 border-rose-200",
};

function cn(...classes: (string | undefined | false)[]) {
  return classes.filter(Boolean).join(" ");
}

// ── Page Component ──────────────────────────────────────────────────────────

export default async function NewsArticlePage(
  { params }: { params: Promise<{ slug: string }> }
) {
  const { slug } = await params;
  const [article, related] = await Promise.all([
    getArticle(slug),
    getRelatedNews(slug),
  ]);

  if (!article) notFound();

  return (
    <>
      <ArticleJsonLD article={article} />

      <div className="min-h-screen bg-[#f5f7fb] pb-20">
        {/* Breadcrumb */}
        <div className="border-b border-white/30 bg-white/70 backdrop-blur-2xl sticky top-0 z-30">
          <div className="max-w-[1280px] mx-auto px-4 py-3 flex items-center gap-1 text-xs text-gray-500 overflow-x-auto scrollbar-none">
            <Link href="/" className="hover:text-blue-600">Home</Link>
            <ChevronRight className="w-3 h-3 text-gray-300" />
            <Link href="/news" className="hover:text-blue-600">News</Link>
            <ChevronRight className="w-3 h-3 text-gray-300" />
            <span className="font-semibold text-gray-800 whitespace-nowrap truncate max-w-[200px]">{article.title}</span>
          </div>
        </div>

        <div className="max-w-[1280px] mx-auto px-4 pt-8">
          <div className="flex flex-col lg:flex-row gap-8">
            {/* ── Main Content ── */}
            <article className="flex-1 min-w-0">
              {/* Back */}
              <Link href="/news" className="inline-flex items-center gap-2 text-sm font-semibold text-gray-500 hover:text-blue-600 mb-6 transition-colors">
                <ArrowLeft className="w-4 h-4" />
                Back to News
              </Link>

              {/* Category + Tags */}
              <div className="flex flex-wrap items-center gap-2 mb-4">
                <span className={cn(
                  "px-3 py-1 rounded-xl text-xs font-black uppercase tracking-wider border",
                  CATEGORY_COLORS[article.category] ?? "bg-gray-50 text-gray-600 border-gray-200"
                )}>
                  {article.category}
                </span>
                {article.tags.map((tag) => (
                  <span key={tag} className="flex items-center gap-1 px-3 py-1 rounded-xl text-xs font-semibold bg-gray-100 text-gray-600">
                    <Tag className="w-3 h-3" />#{tag}
                  </span>
                ))}
              </div>

              {/* Title */}
              <h1 className="text-2xl md:text-3xl lg:text-4xl font-black text-gray-900 leading-tight mb-4">
                {article.title}
              </h1>

              {/* Meta */}
              <div className="flex flex-wrap items-center gap-4 text-sm text-gray-500 mb-6 pb-6 border-b border-gray-100">
                <span className="font-semibold text-gray-700">{article.author}</span>
                <span className="flex items-center gap-1">
                  <Clock className="w-4 h-4" />
                  {article.readTime} min read
                </span>
                {article.views > 0 && (
                  <span className="flex items-center gap-1">
                    <Eye className="w-4 h-4" />
                    {article.views.toLocaleString()} views
                  </span>
                )}
                <span>
                  {new Date(article.publishedAt).toLocaleDateString("en-IN", {
                    day: "numeric", month: "long", year: "numeric",
                  })}
                </span>
              </div>

              {/* Hero Image */}
              {article.imageUrl && (
                <div className="relative w-full aspect-[16/9] rounded-[28px] overflow-hidden mb-8 bg-gray-100">
                  <Image
                    src={article.imageUrl}
                    alt={article.title}
                    fill
                    priority
                    className="object-cover"
                    sizes="(max-width: 1024px) 100vw, 70vw"
                  />
                </div>
              )}

              {/* Summary callout */}
              <div className="rounded-[24px] bg-gradient-to-r from-blue-50 to-cyan-50 border border-blue-100 p-6 mb-8">
                <p className="text-base font-semibold text-gray-700 leading-relaxed">{article.summary}</p>
              </div>

              {/* Article body — rendered HTML from CMS/backend */}
              <div
                className="[&>h1]:text-3xl [&>h1]:font-black [&>h1]:text-gray-900 [&>h1]:mt-8 [&>h1]:mb-4 [&>h2]:text-2xl [&>h2]:font-black [&>h2]:text-gray-900 [&>h2]:mt-8 [&>h2]:mb-3 [&>h3]:text-xl [&>h3]:font-black [&>h3]:text-gray-900 [&>h3]:mt-6 [&>h3]:mb-2 [&>p]:text-gray-700 [&>p]:leading-8 [&>p]:mb-5 [&>ul]:list-disc [&>ul]:pl-6 [&>ul]:mb-5 [&>ul>li]:text-gray-700 [&>ul>li]:leading-7 [&>ul>li]:mb-1 [&>ol]:list-decimal [&>ol]:pl-6 [&>ol]:mb-5 [&>ol>li]:text-gray-700 [&>ol>li]:leading-7 [&>ol>li]:mb-1 [&>blockquote]:border-l-4 [&>blockquote]:border-blue-300 [&>blockquote]:pl-4 [&>blockquote]:italic [&>blockquote]:text-gray-600 [&>blockquote]:my-6 [&>img]:rounded-[20px] [&>img]:w-full [&>img]:my-6 [&>strong]:font-black [&>strong]:text-gray-900 [&>a]:text-blue-600 [&>a]:hover:underline"
                dangerouslySetInnerHTML={{ __html: article.content }}
              />

              {/* Related cars */}
              {article.relatedCarIds.length > 0 && (
                <div className="mt-10 p-6 rounded-[24px] bg-white border border-gray-200/60">
                  <h3 className="text-base font-black text-gray-900 mb-3">Related Cars</h3>
                  <div className="flex flex-wrap gap-2">
                    {article.relatedCarIds.map((id) => (
                      <Link
                        key={id}
                        href={`/cars/${id}`}
                        className="px-4 py-2 rounded-2xl bg-blue-50 border border-blue-200 text-sm font-semibold text-blue-700 hover:bg-blue-100 transition-colors"
                      >
                        View Car →
                      </Link>
                    ))}
                  </div>
                </div>
              )}
            </article>

            {/* ── Sidebar ── */}
            <aside className="w-full lg:w-[320px] shrink-0">
              <div className="lg:sticky lg:top-[88px]">
                <h2 className="text-base font-black text-gray-900 mb-4">More News</h2>
                <div className="space-y-4">
                  {related.map((rel) => (
                    <Link
                      key={rel.id}
                      href={`/news/${rel.slug}`}
                      className="group flex gap-4 rounded-[20px] bg-white border border-gray-200/60 p-4 hover:border-blue-200 hover:shadow-lg transition-all duration-300"
                    >
                      <div className="relative w-20 h-16 rounded-2xl overflow-hidden shrink-0 bg-gray-100">
                        {(rel.thumbnailUrl || rel.imageUrl) && (
                          <Image
                            src={(rel.thumbnailUrl ?? rel.imageUrl)!}
                            alt={rel.title}
                            fill
                            className="object-cover"
                            sizes="80px"
                          />
                        )}
                      </div>
                      <div className="flex-1 min-w-0">
                        <span className={cn(
                          "inline-block mb-1 px-2 py-0.5 rounded-lg text-[10px] font-black uppercase tracking-wider border",
                          CATEGORY_COLORS[rel.category] ?? "bg-gray-50 text-gray-600 border-gray-200"
                        )}>
                          {rel.category}
                        </span>
                        <p className="text-sm font-bold text-gray-800 leading-snug line-clamp-2 group-hover:text-blue-600 transition-colors">
                          {rel.title}
                        </p>
                        <p className="text-xs text-gray-400 mt-1">
                          {new Date(rel.publishedAt).toLocaleDateString("en-IN", { day: "numeric", month: "short" })}
                        </p>
                      </div>
                    </Link>
                  ))}
                </div>

                <div className="mt-6 text-center">
                  <Link
                    href="/news"
                    className="inline-flex items-center gap-2 px-6 py-3 rounded-2xl bg-blue-600 text-white text-sm font-bold hover:bg-blue-700 transition-colors shadow-lg shadow-blue-100"
                  >
                    All News
                    <ChevronRight className="w-4 h-4" />
                  </Link>
                </div>
              </div>
            </aside>
          </div>
        </div>
      </div>
    </>
  );
}
