"use client";

import { useState, useEffect, useCallback } from "react";
import Link from "next/link";
import { motion } from "framer-motion";
import { Sparkles, Clock, Calendar, ChevronLeft, ChevronRight, BookOpen } from "lucide-react";
import { fetchBlogs } from "@/lib/api";
import type { Blog, BlogCategory } from "@/lib/types";
import { cn } from "@/lib/utils";

// ── Helpers ───────────────────────────────────────────────────────────────────

function formatDate(iso: string) {
  try {
    return new Date(iso).toLocaleDateString("en-IN", {
      day: "numeric",
      month: "short",
      year: "numeric",
    });
  } catch {
    return iso;
  }
}

// ── Category config ───────────────────────────────────────────────────────────

const CATEGORIES: Array<{ label: string; value: string }> = [
  { label: "All", value: "all" },
  { label: "Buying Guide", value: "Buying Guide" },
  { label: "Comparison", value: "Comparison" },
  { label: "EV Guide", value: "EV Guide" },
  { label: "Review", value: "Review" },
  { label: "News", value: "News" },
  { label: "Upcoming", value: "Upcoming" },
  { label: "Tips", value: "Tips" },
  { label: "Maintenance", value: "Maintenance" },
];

const CATEGORY_COLORS: Record<string, { bg: string; text: string; bar: string }> = {
  "Buying Guide": { bg: "bg-blue-50",   text: "text-blue-600",   bar: "from-blue-500 to-blue-400" },
  "Comparison":   { bg: "bg-purple-50", text: "text-purple-600", bar: "from-purple-500 to-violet-400" },
  "EV Guide":     { bg: "bg-green-50",  text: "text-green-600",  bar: "from-green-500 to-emerald-400" },
  "Review":       { bg: "bg-orange-50", text: "text-orange-600", bar: "from-orange-500 to-amber-400" },
  "News":         { bg: "bg-red-50",    text: "text-red-600",    bar: "from-red-500 to-rose-400" },
  "Upcoming":     { bg: "bg-amber-50",  text: "text-amber-600",  bar: "from-amber-500 to-yellow-400" },
  "Tips":         { bg: "bg-teal-50",   text: "text-teal-600",   bar: "from-teal-500 to-cyan-400" },
  "Maintenance":  { bg: "bg-slate-50",  text: "text-slate-600",  bar: "from-slate-500 to-gray-400" },
};

function getCategoryColors(cat: string) {
  return CATEGORY_COLORS[cat] ?? { bg: "bg-blue-50", text: "text-blue-600", bar: "from-blue-500 to-cyan-400" };
}

// ── BlogCard ──────────────────────────────────────────────────────────────────

function BlogCard({ blog, index }: { blog: Blog; index: number }) {
  const colors = getCategoryColors(blog.category);
  return (
    <motion.div
      initial={{ opacity: 0, y: 20 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ duration: 0.35, delay: index * 0.05 }}
    >
      <Link href={`/blogs/${blog.slug}`}>
        <div className="bg-white rounded-2xl overflow-hidden shadow-sm hover:shadow-md transition-all duration-300 border border-gray-100 h-full flex flex-col group">
          {/* Category color bar */}
          <div className={cn("h-1 bg-gradient-to-r flex-shrink-0", colors.bar)} />
          <div className="p-5 flex flex-col flex-1">
            <div className="flex items-center gap-2 flex-wrap">
              <span className={cn("text-xs font-bold uppercase tracking-wider px-2 py-1 rounded-full", colors.bg, colors.text)}>
                {blog.category}
              </span>
              {blog.aiGenerated && (
                <span className="text-xs font-bold text-purple-600 bg-purple-50 px-2 py-1 rounded-full flex items-center gap-1">
                  <Sparkles className="w-3 h-3" />
                  Editorial
                </span>
              )}
            </div>
            <h3 className="text-base font-black text-gray-900 mt-3 mb-2 line-clamp-2 group-hover:text-blue-600 transition-colors">
              {blog.title}
            </h3>
            <p className="text-sm text-gray-500 line-clamp-2 flex-1">{blog.excerpt}</p>
            <div className="flex items-center justify-between mt-4 pt-3 border-t border-gray-50">
              <span className="text-xs text-gray-400 flex items-center gap-1">
                <Clock className="w-3 h-3" />
                {blog.readTime} min read
              </span>
              <span className="text-xs text-gray-400 flex items-center gap-1">
                <Calendar className="w-3 h-3" />
                {formatDate(blog.publishedAt)}
              </span>
            </div>
          </div>
        </div>
      </Link>
    </motion.div>
  );
}

// ── Empty state ───────────────────────────────────────────────────────────────

function EmptyState() {
  return (
    <div className="col-span-full flex flex-col items-center justify-center py-20 text-center">
      <div className="w-16 h-16 rounded-2xl bg-blue-50 flex items-center justify-center mb-4">
        <BookOpen className="w-8 h-8 text-blue-400" />
      </div>
      <h3 className="text-lg font-black text-gray-900 mb-2">No blog posts yet</h3>
      <p className="text-sm text-gray-400 max-w-xs">
        Blog posts will appear here once content is published. Check back soon!
      </p>
    </div>
  );
}

// ── Skeleton card ─────────────────────────────────────────────────────────────

function BlogCardSkeleton() {
  return (
    <div className="bg-white rounded-2xl overflow-hidden border border-gray-100 animate-pulse">
      <div className="h-1 bg-gray-200" />
      <div className="p-5 space-y-3">
        <div className="h-4 bg-gray-100 rounded-full w-24" />
        <div className="h-5 bg-gray-100 rounded-lg w-full" />
        <div className="h-5 bg-gray-100 rounded-lg w-3/4" />
        <div className="h-4 bg-gray-100 rounded-lg w-full" />
        <div className="h-4 bg-gray-100 rounded-lg w-2/3" />
        <div className="flex justify-between pt-3">
          <div className="h-3 bg-gray-100 rounded w-16" />
          <div className="h-3 bg-gray-100 rounded w-20" />
        </div>
      </div>
    </div>
  );
}

// ── Main Page ─────────────────────────────────────────────────────────────────

export default function BlogsPage() {
  const [blogs, setBlogs] = useState<Blog[]>([]);
  const [total, setTotal] = useState(0);
  const [totalPages, setTotalPages] = useState(1);
  const [page, setPage] = useState(1);
  const [activeCategory, setActiveCategory] = useState("all");
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const LIMIT = 12;

  const loadBlogs = useCallback(async (cat: string, p: number) => {
    setLoading(true);
    setError(null);
    try {
      const params: { page: number; limit: number; category?: string; status: string } = {
        page: p,
        limit: LIMIT,
        status: "published",
      };
      if (cat !== "all") params.category = cat;
      const res = await fetchBlogs(params);
      setBlogs(res.blogs ?? []);
      setTotal(res.total ?? 0);
      setTotalPages(res.totalPages ?? 1);
    } catch {
      setError("Failed to load blog posts. Please try again.");
      setBlogs([]);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    loadBlogs(activeCategory, page);
  }, [activeCategory, page, loadBlogs]);

  function handleCategory(cat: string) {
    setActiveCategory(cat);
    setPage(1);
  }

  return (
    <div className="min-h-screen bg-gray-50">
      {/* Hero */}
      <section className="bg-gradient-to-br from-gray-900 via-blue-950 to-gray-900 text-white py-16 px-4">
        <div className="max-w-6xl mx-auto text-center">
          <motion.div
            initial={{ opacity: 0, y: -20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.5 }}
          >
            <span className="inline-flex items-center gap-2 text-xs font-bold uppercase tracking-widest text-blue-300 bg-blue-950/60 border border-blue-800 px-4 py-2 rounded-full mb-6">
              <Sparkles className="w-3.5 h-3.5" />
              Expert Automotive Content
            </span>
            <h1 className="text-4xl sm:text-5xl font-black mb-4 leading-tight">
              DriveHub Automotive Blog
            </h1>
            <p className="text-lg text-gray-300 max-w-2xl mx-auto">
              Expert reviews, buying guides &amp; automotive news — written by automotive experts
            </p>
            {total > 0 && (
              <p className="text-sm text-blue-300 mt-4 font-medium">{total} articles and counting</p>
            )}
          </motion.div>
        </div>
      </section>

      {/* Category filter */}
      <div className="sticky top-0 z-10 bg-white border-b border-gray-100 shadow-sm">
        <div className="max-w-6xl mx-auto px-4 overflow-x-auto">
          <div className="flex gap-1 py-3 w-max min-w-full">
            {CATEGORIES.map((cat) => (
              <button
                key={cat.value}
                onClick={() => handleCategory(cat.value)}
                className={cn(
                  "px-4 py-2 rounded-xl text-sm font-bold whitespace-nowrap transition-all duration-200",
                  activeCategory === cat.value
                    ? "bg-gradient-to-r from-blue-600 to-cyan-500 text-white shadow-md shadow-blue-100"
                    : "text-gray-600 hover:bg-gray-100 hover:text-gray-900"
                )}
              >
                {cat.label}
              </button>
            ))}
          </div>
        </div>
      </div>

      {/* Content */}
      <div className="max-w-6xl mx-auto px-4 py-10">
        {error && (
          <div className="mb-6 rounded-2xl bg-red-50 border border-red-200 p-4 text-sm text-red-700">
            {error}
          </div>
        )}

        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
          {loading
            ? Array.from({ length: 6 }).map((_, i) => <BlogCardSkeleton key={i} />)
            : blogs.length === 0
            ? <EmptyState />
            : blogs.map((blog, i) => <BlogCard key={blog.id} blog={blog} index={i} />)
          }
        </div>

        {/* Pagination */}
        {!loading && totalPages > 1 && (
          <div className="flex items-center justify-center gap-3 mt-12">
            <button
              onClick={() => setPage((p) => Math.max(1, p - 1))}
              disabled={page === 1}
              className="p-2.5 rounded-xl border border-gray-200 bg-white text-gray-600 disabled:opacity-40 disabled:cursor-not-allowed hover:border-blue-300 hover:text-blue-600 transition-all"
            >
              <ChevronLeft className="w-5 h-5" />
            </button>

            <div className="flex items-center gap-2">
              {Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
                let pageNum: number;
                if (totalPages <= 5) {
                  pageNum = i + 1;
                } else if (page <= 3) {
                  pageNum = i + 1;
                } else if (page >= totalPages - 2) {
                  pageNum = totalPages - 4 + i;
                } else {
                  pageNum = page - 2 + i;
                }
                return (
                  <button
                    key={pageNum}
                    onClick={() => setPage(pageNum)}
                    className={cn(
                      "w-10 h-10 rounded-xl text-sm font-bold transition-all",
                      page === pageNum
                        ? "bg-gradient-to-r from-blue-600 to-cyan-500 text-white shadow-md"
                        : "bg-white border border-gray-200 text-gray-600 hover:border-blue-300"
                    )}
                  >
                    {pageNum}
                  </button>
                );
              })}
            </div>

            <button
              onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
              disabled={page === totalPages}
              className="p-2.5 rounded-xl border border-gray-200 bg-white text-gray-600 disabled:opacity-40 disabled:cursor-not-allowed hover:border-blue-300 hover:text-blue-600 transition-all"
            >
              <ChevronRight className="w-5 h-5" />
            </button>
          </div>
        )}
      </div>
    </div>
  );
}
