"use client";

import { useState, useEffect, useCallback } from "react";
import Image from "next/image";
import {
  Newspaper,
  Sparkles,
  RefreshCw,
  Loader2,
  CheckCircle2,
  Clock,
  Tag,
  ChevronLeft,
  ChevronRight,
  ExternalLink,
  Zap,
} from "lucide-react";
import { fetchNews, generateNews } from "@/lib/api";
import type { NewsArticle } from "@/lib/types";
import { cn } from "@/lib/utils";

// ── helpers ───────────────────────────────────────────────────────────────────

function fmt(iso: string | null | undefined) {
  if (!iso) return "—";
  try {
    return new Date(iso).toLocaleString("en-IN", {
      day: "numeric", month: "short", year: "numeric",
      hour: "2-digit", minute: "2-digit",
    });
  } catch { return "—"; }
}

const CATEGORIES = ["All", "Launch", "Facelift", "EV", "Industry", "Review", "Comparison"];

const CAT_COLORS: Record<string, string> = {
  Launch:     "bg-blue-100 text-blue-700",
  Facelift:   "bg-violet-100 text-violet-700",
  EV:         "bg-green-100 text-green-700",
  Industry:   "bg-amber-100 text-amber-700",
  Review:     "bg-pink-100 text-pink-700",
  Comparison: "bg-cyan-100 text-cyan-700",
};

// ── Article row ───────────────────────────────────────────────────────────────

function ArticleRow({ article }: { article: NewsArticle }) {
  return (
    <div className="flex items-start gap-3 sm:gap-4 px-3 sm:px-5 py-4 hover:bg-gray-50/70 transition-colors border-b border-gray-100 last:border-0 min-w-0">
      {/* Thumbnail */}
      <div className="shrink-0 w-14 h-10 sm:w-20 sm:h-14 rounded-xl overflow-hidden bg-gray-100 relative">
        {article.imageUrl ? (
          <Image
            src={article.imageUrl}
            alt={article.title}
            fill
            className="object-cover"
            sizes="80px"
            unoptimized
          />
        ) : (
          <div className="w-full h-full flex items-center justify-center">
            <Newspaper className="w-5 h-5 sm:w-6 sm:h-6 text-gray-300" />
          </div>
        )}
      </div>

      {/* Content */}
      <div className="flex-1 min-w-0">
        <h3 className="text-sm font-bold text-gray-900 line-clamp-2 leading-snug break-words">
          {article.title}
        </h3>
        <div className="flex items-center gap-2 mt-1.5 flex-wrap">
          {article.category && (
            <span className={cn("text-[10px] font-bold px-2 py-0.5 rounded-full shrink-0", CAT_COLORS[article.category] ?? "bg-gray-100 text-gray-600")}>
              {article.category}
            </span>
          )}
          {article.tags?.slice(0, 3).map((t: string) => (
            <span key={t} className="text-[10px] font-medium text-gray-500 bg-gray-100 px-2 py-0.5 rounded-full max-w-[9rem] truncate">
              {t}
            </span>
          ))}
          <span className="text-[10px] text-gray-400 w-full sm:w-auto sm:ml-auto">{fmt(article.publishedAt)}</span>
        </div>
      </div>

      {/* Actions */}
      <div className="shrink-0 flex items-center self-center">
        {article.slug && (
          <a
            href={`/news/${article.slug}`}
            target="_blank"
            rel="noopener noreferrer"
            aria-label="Open article"
            className="inline-flex items-center justify-center min-h-11 min-w-11 rounded-xl hover:bg-blue-50 text-gray-400 hover:text-blue-600 transition-colors"
          >
            <ExternalLink className="w-4 h-4" />
          </a>
        )}
      </div>
    </div>
  );
}

// ── Main page ─────────────────────────────────────────────────────────────────

export default function AdminNewsPage() {
  const [articles, setArticles] = useState<NewsArticle[]>([]);
  const [total, setTotal]       = useState(0);
  const [page, setPage]         = useState(1);
  const [category, setCategory] = useState("All");
  const [loading, setLoading]   = useState(true);
  const [generating, setGenerating] = useState(false);
  const [genMsg, setGenMsg]     = useState<string | null>(null);

  const PER_PAGE = 15;
  const totalPages = Math.max(1, Math.ceil(total / PER_PAGE));

  const load = useCallback(async () => {
    setLoading(true);
    try {
      const res = await fetchNews({
        category: category === "All" ? undefined : category,
        page,
        limit: PER_PAGE,
      });
      setArticles(res.articles ?? []);
      setTotal(res.total ?? 0);
    } catch (e) {
      console.error(e);
    } finally {
      setLoading(false);
    }
  }, [category, page]);

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

  async function handleGenerate() {
    setGenerating(true);
    setGenMsg(null);
    try {
      const res = await generateNews();
      setGenMsg(`Generated ${res?.generated ?? 0} articles.`);
      await load();
    } catch {
      setGenMsg("Generation failed.");
    } finally {
      setGenerating(false);
    }
  }

  return (
    <div className="p-4 sm:p-6 max-w-[1200px] mx-auto min-w-0 overflow-x-hidden pb-[env(safe-area-inset-bottom,0px)]">
      {/* Header */}
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-6 min-w-0">
        <div className="min-w-0">
          <h1 className="text-xl sm:text-2xl font-black text-gray-900 flex items-center gap-2 min-w-0">
            <Newspaper className="w-6 h-6 text-blue-600 shrink-0" />
            <span className="truncate">News Engine</span>
          </h1>
          <p className="text-sm text-gray-500 mt-0.5 break-words">
            {total.toLocaleString()} articles · auto-discovers launches, facelifts, EV news every 24h
          </p>
        </div>
        <div className="flex flex-wrap items-center gap-2 sm:gap-3 shrink-0">
          <button
            onClick={load}
            disabled={loading}
            className="inline-flex items-center justify-center gap-2 min-h-11 px-4 py-2.5 rounded-2xl border border-gray-200 bg-white text-sm font-bold text-gray-700 hover:border-gray-300 transition-all disabled:opacity-50"
          >
            <RefreshCw className={cn("w-4 h-4", loading && "animate-spin")} />
            Refresh
          </button>
          <button
            onClick={handleGenerate}
            disabled={generating}
            className="inline-flex items-center justify-center gap-2 min-h-11 px-4 py-2.5 rounded-2xl bg-gradient-to-r from-blue-600 to-cyan-500 text-white text-sm font-bold shadow-lg shadow-blue-200 hover:opacity-90 transition-all disabled:opacity-60"
          >
            {generating ? <Loader2 className="w-4 h-4 animate-spin" /> : <Sparkles className="w-4 h-4" />}
            Generate News
          </button>
        </div>
      </div>

      {/* Gen message */}
      {genMsg && (
        <div className="mb-4 flex items-start gap-2 px-4 py-3 rounded-2xl bg-green-50 border border-green-100 text-sm text-green-700 font-medium min-w-0">
          <CheckCircle2 className="w-4 h-4 shrink-0 mt-0.5" />
          <span className="break-words min-w-0">{genMsg}</span>
        </div>
      )}

      {/* Stats row */}
      <div className="grid grid-cols-2 sm:grid-cols-4 gap-3 sm:gap-4 mb-6">
        {[
          { label: "Total Articles", value: total, icon: Newspaper, color: "text-blue-600" },
          { label: "Categories",     value: CATEGORIES.length - 1, icon: Tag, color: "text-violet-600" },
          { label: "This Month",     value: articles.filter(a => {
            const d = new Date(a.publishedAt ?? "");
            const now = new Date();
            return d.getMonth() === now.getMonth() && d.getFullYear() === now.getFullYear();
          }).length, icon: Clock, color: "text-amber-600" },
          { label: "Featured",       value: articles.filter(a => a.isFeatured).length, icon: Zap, color: "text-green-600" },
        ].map(({ label, value, icon: Icon, color }) => (
          <div key={label} className="bg-white rounded-2xl border border-gray-100 p-3 sm:p-4 shadow-sm min-w-0">
            <div className="flex items-center gap-2 mb-1 min-w-0">
              <Icon className={cn("w-4 h-4 shrink-0", color)} />
              <span className="text-[10px] sm:text-xs font-bold text-gray-500 uppercase tracking-wide truncate">{label}</span>
            </div>
            <p className="text-2xl font-black text-gray-900 tabular-nums">{value}</p>
          </div>
        ))}
      </div>

      {/* Category filter */}
      <div className="flex items-center gap-2 mb-4 flex-wrap">
        {CATEGORIES.map(c => (
          <button
            key={c}
            onClick={() => { setCategory(c); setPage(1); }}
            className={cn(
              "min-h-11 px-4 py-2 rounded-2xl text-sm font-bold transition-all",
              category === c
                ? "bg-blue-600 text-white shadow-lg shadow-blue-200"
                : "bg-white border border-gray-200 text-gray-600 hover:border-blue-200"
            )}
          >
            {c}
          </button>
        ))}
      </div>

      {/* Articles list */}
      <div className="bg-white rounded-2xl border border-gray-100 shadow-sm overflow-hidden min-w-0">
        {loading ? (
          <div className="flex items-center justify-center py-16">
            <Loader2 className="w-6 h-6 animate-spin text-blue-500" />
          </div>
        ) : articles.length === 0 ? (
          <div className="flex flex-col items-center justify-center py-16 text-center px-4">
            <Newspaper className="w-10 h-10 text-gray-200 mb-3" />
            <p className="text-sm font-semibold text-gray-400">No articles found</p>
            <p className="text-xs text-gray-300 mt-1 break-words">Try generating news or changing the category filter</p>
          </div>
        ) : (
          <>
            {articles.map(a => <ArticleRow key={a.id ?? a.slug} article={a} />)}
          </>
        )}
      </div>

      {/* Pagination */}
      {totalPages > 1 && (
        <div className="flex flex-wrap items-center justify-between gap-2 mt-4 px-1 min-w-0">
          <button
            onClick={() => setPage(p => Math.max(1, p - 1))}
            disabled={page === 1}
            className="inline-flex items-center gap-1 min-h-11 px-3 py-2 rounded-xl text-sm font-bold text-gray-600 hover:bg-gray-100 disabled:opacity-40 transition-all"
          >
            <ChevronLeft className="w-4 h-4" /> Prev
          </button>
          <span className="text-sm font-medium text-gray-500 text-center order-first w-full sm:order-none sm:w-auto">
            Page {page} of {totalPages} · {total} articles
          </span>
          <button
            onClick={() => setPage(p => Math.min(totalPages, p + 1))}
            disabled={page === totalPages}
            className="inline-flex items-center gap-1 min-h-11 px-3 py-2 rounded-xl text-sm font-bold text-gray-600 hover:bg-gray-100 disabled:opacity-40 transition-all ml-auto sm:ml-0"
          >
            Next <ChevronRight className="w-4 h-4" />
          </button>
        </div>
      )}
    </div>
  );
}
