"use client";

import { useState, useEffect, useCallback } from "react";
import Link from "next/link";
import Image from "next/image";
import { motion } from "framer-motion";
import { Clock, Eye, Tag, ChevronRight, Newspaper } from "lucide-react";
import type { NewsArticle } from "@/lib/types";
import { fetchNews, fetchNewsCategories } from "@/lib/api";
import { cn } from "@/lib/utils";

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 ArticleCard({ article }: { article: NewsArticle }) {
  return (
    <motion.div
      whileHover={{ y: -4 }}
      transition={{ duration: 0.2 }}
      className="group rounded-[28px] overflow-hidden bg-white border border-gray-200/60 shadow-[0_4px_20px_rgba(0,0,0,0.05)] hover:shadow-[0_12px_40px_rgba(0,0,0,0.10)] transition-all duration-300"
    >
      <Link href={`/news/${article.slug}`} className="block">
        <div className="relative aspect-[16/9] bg-gradient-to-br from-gray-100 to-gray-50 overflow-hidden">
          {article.thumbnailUrl || article.imageUrl ? (
            <Image
              src={(article.thumbnailUrl ?? article.imageUrl)!}
              alt={article.title}
              fill
              className="object-cover transition-transform duration-500 group-hover:scale-105"
              sizes="(max-width: 768px) 100vw, 33vw"
            />
          ) : (
            <div className="absolute inset-0 flex items-center justify-center">
              <Newspaper className="w-12 h-12 text-gray-300" />
            </div>
          )}
          {article.isFeatured && (
            <div className="absolute top-3 left-3 px-3 py-1 rounded-xl bg-gradient-to-r from-amber-400 to-orange-400 text-white text-[11px] font-black uppercase tracking-wider shadow-md">
              Featured
            </div>
          )}
        </div>

        <div className="p-5">
          <div className="flex items-center gap-2 mb-3">
            <span className={cn(
              "px-2.5 py-1 rounded-xl text-[11px] font-black uppercase tracking-wider border",
              CATEGORY_COLORS[article.category] ?? "bg-gray-50 text-gray-600 border-gray-200"
            )}>
              {article.category}
            </span>
            {article.tags.slice(0, 2).map((tag) => (
              <span key={tag} className="px-2.5 py-1 rounded-xl text-[11px] font-semibold bg-gray-100 text-gray-600">
                #{tag}
              </span>
            ))}
          </div>

          <h2 className="text-base font-black text-gray-900 leading-snug mb-2 group-hover:text-blue-600 transition-colors line-clamp-2">
            {article.title}
          </h2>
          <p className="text-sm text-gray-500 leading-relaxed line-clamp-2 mb-4">
            {article.summary}
          </p>

          <div className="flex items-center justify-between text-xs text-gray-400">
            <div className="flex items-center gap-3">
              <span className="flex items-center gap-1">
                <Clock className="w-3 h-3" />
                {article.readTime} min read
              </span>
              {article.views > 0 && (
                <span className="flex items-center gap-1">
                  <Eye className="w-3 h-3" />
                  {article.views.toLocaleString()}
                </span>
              )}
            </div>
            <span>{new Date(article.publishedAt).toLocaleDateString("en-IN", { day: "numeric", month: "short", year: "numeric" })}</span>
          </div>
        </div>
      </Link>
    </motion.div>
  );
}

function FeaturedArticleCard({ article }: { article: NewsArticle }) {
  return (
    <Link href={`/news/${article.slug}`} className="group block relative rounded-[32px] overflow-hidden aspect-[16/7] bg-gray-900 shadow-2xl">
      {(article.imageUrl || article.thumbnailUrl) && (
        <Image
          src={(article.imageUrl ?? article.thumbnailUrl)!}
          alt={article.title}
          fill
          priority
          className="object-cover transition-transform duration-700 group-hover:scale-105"
          sizes="100vw"
        />
      )}
      <div className="absolute inset-0 bg-gradient-to-t from-black/80 via-black/30 to-transparent" />
      <div className="absolute bottom-0 left-0 p-8">
        <span className={cn(
          "inline-block mb-3 px-3 py-1 rounded-xl text-[11px] font-black uppercase tracking-wider border",
          CATEGORY_COLORS[article.category] ?? "bg-gray-50 text-gray-600 border-gray-200"
        )}>
          {article.category}
        </span>
        <h2 className="text-2xl md:text-3xl font-black text-white leading-tight mb-2 max-w-2xl">
          {article.title}
        </h2>
        <p className="text-sm text-white/70 line-clamp-2 max-w-xl mb-4">{article.summary}</p>
        <div className="flex items-center gap-3 text-xs text-white/60">
          <span className="flex items-center gap-1"><Clock className="w-3 h-3" />{article.readTime} min read</span>
          <span>{new Date(article.publishedAt).toLocaleDateString("en-IN", { day: "numeric", month: "short", year: "numeric" })}</span>
        </div>
      </div>
    </Link>
  );
}

export default function NewsPage() {
  const [articles,    setArticles]    = useState<NewsArticle[]>([]);
  const [featured,   setFeatured]    = useState<NewsArticle | null>(null);
  const [categories, setCategories]  = useState<string[]>([]);
  const [active,     setActive]      = useState("All");
  const [page,       setPage]        = useState(1);
  const [totalPages, setTotalPages]  = useState(1);
  const [loading,    setLoading]     = useState(true);

  useEffect(() => {
    fetchNewsCategories().then((d) => setCategories(["All", ...d.categories]));
  }, []);

  const load = useCallback(async () => {
    setLoading(true);
    try {
      const data = await fetchNews({ category: active === "All" ? undefined : active, page, limit: 12 });
      setArticles(data.articles);
      setTotalPages(data.totalPages);

      if (page === 1) {
        const feat = data.articles.find((a) => a.isFeatured);
        setFeatured(feat ?? null);
      }
    } finally {
      setLoading(false);
    }
  }, [active, page]);

  useEffect(() => { load(); }, [load]);

  const gridArticles = featured && page === 1
    ? articles.filter((a) => a.id !== featured.id)
    : articles;

  return (
    <div className="min-h-screen bg-[#f5f7fb] pb-20">
      {/* Header */}
      <div className="bg-white border-b border-gray-100">
        <div className="max-w-[1280px] mx-auto px-4 py-8">
          <div className="flex items-center gap-2 text-xs text-gray-500 mb-4">
            <Link href="/" className="hover:text-blue-600">Home</Link>
            <ChevronRight className="w-3 h-3" />
            <span className="font-semibold text-gray-800">News</span>
          </div>
          <h1 className="text-3xl font-black text-gray-900 mb-2">Automotive News</h1>
          <p className="text-gray-500">Latest launches, reviews, and industry updates</p>
        </div>
      </div>

      <div className="max-w-[1280px] mx-auto px-4 py-8">
        {/* Category Pills */}
        <div className="flex gap-2 overflow-x-auto scrollbar-none pb-2 mb-8">
          {categories.map((cat) => (
            <button
              key={cat}
              onClick={() => { setActive(cat); setPage(1); }}
              className={cn(
                "shrink-0 px-5 py-2.5 rounded-2xl text-sm font-bold border transition-all duration-200",
                active === cat
                  ? "bg-blue-600 text-white border-blue-600 shadow-lg shadow-blue-100"
                  : "bg-white text-gray-600 border-gray-200 hover:border-blue-200 hover:text-blue-600"
              )}
            >
              {cat}
            </button>
          ))}
        </div>

        {/* Featured Hero */}
        {featured && page === 1 && !loading && (
          <div className="mb-8">
            <FeaturedArticleCard article={featured} />
          </div>
        )}

        {/* Grid */}
        {loading ? (
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
            {Array.from({ length: 9 }).map((_, i) => (
              <div key={i} className="rounded-[28px] bg-white border border-gray-200/60 overflow-hidden animate-pulse">
                <div className="aspect-[16/9] bg-gray-100" />
                <div className="p-5 space-y-3">
                  <div className="h-3 bg-gray-100 rounded-full w-1/3" />
                  <div className="h-4 bg-gray-100 rounded-full" />
                  <div className="h-4 bg-gray-100 rounded-full w-4/5" />
                  <div className="h-3 bg-gray-100 rounded-full w-1/2" />
                </div>
              </div>
            ))}
          </div>
        ) : gridArticles.length > 0 ? (
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
            {gridArticles.map((article) => (
              <ArticleCard key={article.id} article={article} />
            ))}
          </div>
        ) : (
          <div className="text-center py-20 text-gray-400">
            <Newspaper className="w-12 h-12 mx-auto mb-3 opacity-30" />
            <p className="font-semibold">No articles found</p>
          </div>
        )}

        {/* Pagination */}
        {totalPages > 1 && (
          <div className="flex items-center justify-center gap-2 mt-10">
            <button
              onClick={() => setPage((p) => Math.max(1, p - 1))}
              disabled={page === 1}
              className="px-5 py-2.5 rounded-2xl border border-gray-200 bg-white text-sm font-semibold text-gray-700 hover:border-blue-300 disabled:opacity-40 transition-all"
            >
              Previous
            </button>
            <span className="px-4 py-2 text-sm font-bold text-gray-600">
              {page} / {totalPages}
            </span>
            <button
              onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
              disabled={page === totalPages}
              className="px-5 py-2.5 rounded-2xl border border-gray-200 bg-white text-sm font-semibold text-gray-700 hover:border-blue-300 disabled:opacity-40 transition-all"
            >
              Next
            </button>
          </div>
        )}
      </div>
    </div>
  );
}
