"use client";

import { useState, useEffect, useCallback } from "react";
import { motion, AnimatePresence } from "framer-motion";
import {
  FileText,
  Sparkles,
  RefreshCw,
  Loader2,
  Trash2,
  Eye,
  CheckCircle2,
  Clock,
  ChevronLeft,
  ChevronRight,
  X,
} from "lucide-react";
import {
  fetchBlogs,
  fetchBlogStats,
  generateBlog,
  updateBlog,
  deleteBlog,
} from "@/lib/api";
import type { Blog, BlogStatus, BlogStats, 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;
  }
}

// ── Constants ─────────────────────────────────────────────────────────────────

const CATEGORIES: BlogCategory[] = [
  "Buying Guide",
  "Comparison",
  "EV Guide",
  "Review",
  "News",
  "Upcoming",
  "Maintenance",
  "Tips",
];

const STATUS_CONFIG: Record<BlogStatus, { label: string; bg: string; text: string; border: string }> = {
  published: { label: "Published", bg: "bg-green-50",  text: "text-green-700",  border: "border-green-200" },
  draft:     { label: "Draft",     bg: "bg-amber-50",  text: "text-amber-700",  border: "border-amber-200" },
  archived:  { label: "Archived",  bg: "bg-gray-100",  text: "text-gray-500",   border: "border-gray-200" },
};

// ── StatCard ──────────────────────────────────────────────────────────────────

function StatCard({
  icon: Icon,
  label,
  value,
  color = "blue",
}: {
  icon: React.ElementType;
  label: string;
  value: number | string | undefined;
  color?: "blue" | "green" | "amber" | "purple" | "orange";
}) {
  const gradients = {
    blue:   "from-blue-500 to-blue-600 shadow-blue-100",
    green:  "from-green-500 to-emerald-500 shadow-green-100",
    amber:  "from-amber-400 to-orange-500 shadow-amber-100",
    purple: "from-violet-500 to-purple-500 shadow-violet-100",
    orange: "from-orange-500 to-red-500 shadow-orange-100",
  };
  return (
    <div className="rounded-[24px] bg-white border border-gray-200/60 p-4 sm:p-5 shadow-[0_4px_20px_rgba(0,0,0,0.05)] min-w-0">
      <div className={cn("w-10 h-10 rounded-2xl bg-gradient-to-br flex items-center justify-center mb-3 shadow-lg", gradients[color])}>
        <Icon className="w-5 h-5 text-white" />
      </div>
      <p className="text-2xl font-black text-gray-900 break-words">{value ?? "—"}</p>
      <p className="text-xs font-bold text-gray-500 mt-1 break-words">{label}</p>
    </div>
  );
}

// ── StatusBadge ───────────────────────────────────────────────────────────────

function StatusBadge({ status }: { status: BlogStatus }) {
  const cfg = STATUS_CONFIG[status] ?? STATUS_CONFIG.draft;
  return (
    <span className={cn("text-xs font-bold px-2.5 py-1 rounded-full border", cfg.bg, cfg.text, cfg.border)}>
      {cfg.label}
    </span>
  );
}

// ── GenerateModal ─────────────────────────────────────────────────────────────

function GenerateModal({
  onClose,
  onSuccess,
}: {
  onClose: () => void;
  onSuccess: (blog: Blog) => void;
}) {
  const [category, setCategory] = useState<BlogCategory | "">("");
  const [topic, setTopic] = useState("");
  const [generating, setGenerating] = useState(false);
  const [error, setError] = useState<string | null>(null);

  async function handleGenerate() {
    setGenerating(true);
    setError(null);
    try {
      const blog = await generateBlog({
        category: category || undefined,
        topic: topic.trim() || undefined,
      });
      onSuccess(blog);
      onClose();
    } catch (e: unknown) {
      setError(e instanceof Error ? e.message : "Generation failed. Please try again.");
    } finally {
      setGenerating(false);
    }
  }

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 pt-[calc(1rem+env(safe-area-inset-top,0px))] pb-[calc(1rem+env(safe-area-inset-bottom,0px))]">
      <div className="absolute inset-0 bg-black/50 backdrop-blur-sm" onClick={onClose} />
      <motion.div
        initial={{ opacity: 0, scale: 0.95, y: 10 }}
        animate={{ opacity: 1, scale: 1, y: 0 }}
        exit={{ opacity: 0, scale: 0.95, y: 10 }}
        transition={{ duration: 0.2 }}
        className="relative bg-white rounded-[28px] shadow-2xl w-full max-w-md p-5 sm:p-6 z-10 max-h-[min(90dvh,calc(100dvh-2rem))] overflow-y-auto"
      >
        <button
          onClick={onClose}
          className="absolute top-3 right-3 p-2.5 rounded-xl hover:bg-gray-100 text-gray-400 hover:text-gray-600 transition-colors"
          aria-label="Close"
        >
          <X className="w-5 h-5" />
        </button>

        <div className="flex items-center gap-3 mb-6 pr-10 min-w-0">
          <div className="w-10 h-10 rounded-2xl bg-gradient-to-br from-purple-500 to-violet-500 flex items-center justify-center shadow-lg shadow-purple-100 shrink-0">
            <Sparkles className="w-5 h-5 text-white" />
          </div>
          <div className="min-w-0">
            <h3 className="text-lg font-black text-gray-900 break-words">Generate AI Blog Post</h3>
            <p className="text-xs text-gray-400">Powered by Claude AI</p>
          </div>
        </div>

        <div className="space-y-4">
          <div>
            <label className="block text-sm font-bold text-gray-700 mb-2">Category</label>
            <select
              value={category}
              onChange={(e) => setCategory(e.target.value as BlogCategory | "")}
              className="w-full min-w-0 px-4 py-3 rounded-2xl border border-gray-200 bg-gray-50 text-sm font-medium text-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
            >
              <option value="">Random category</option>
              {CATEGORIES.map((cat) => (
                <option key={cat} value={cat}>{cat}</option>
              ))}
            </select>
          </div>

          <div>
            <label className="block text-sm font-bold text-gray-700 mb-2">
              Custom Topic <span className="text-gray-400 font-normal">(optional)</span>
            </label>
            <input
              type="text"
              value={topic}
              onChange={(e) => setTopic(e.target.value)}
              placeholder="e.g. Best SUVs under 15 lakhs in 2025"
              className="w-full min-w-0 px-4 py-3 rounded-2xl border border-gray-200 bg-gray-50 text-sm font-medium placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
            />
          </div>

          {error && (
            <div className="rounded-xl bg-red-50 border border-red-200 p-3 text-sm text-red-600 break-words">
              {error}
            </div>
          )}

          {generating && (
            <div className="rounded-2xl bg-blue-50 border border-blue-100 p-4 text-sm text-blue-700 flex items-start gap-3 min-w-0">
              <Loader2 className="w-5 h-5 animate-spin shrink-0 mt-0.5" />
              <span className="min-w-0 break-words">AI is writing your blog post… (this may take ~30 seconds)</span>
            </div>
          )}

          <motion.button
            whileTap={{ scale: 0.97 }}
            onClick={handleGenerate}
            disabled={generating}
            className={cn(
              "w-full flex items-center justify-center gap-2 py-3.5 rounded-2xl font-bold text-sm transition-all min-h-[44px]",
              generating
                ? "bg-gray-100 text-gray-400 cursor-not-allowed"
                : "bg-gradient-to-r from-purple-600 to-violet-500 text-white shadow-xl shadow-purple-100 hover:shadow-2xl"
            )}
          >
            {generating ? (
              <><Loader2 className="w-4 h-4 animate-spin" /> Generating…</>
            ) : (
              <><Sparkles className="w-4 h-4" /> Generate Blog Post</>
            )}
          </motion.button>
        </div>
      </motion.div>
    </div>
  );
}

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

const LIMIT = 20;

export default function AdminBlogsPage() {
  const [blogs, setBlogs] = useState<Blog[]>([]);
  const [stats, setStats] = useState<BlogStats | null>(null);
  const [total, setTotal] = useState(0);
  const [totalPages, setTotalPages] = useState(1);
  const [page, setPage] = useState(1);
  const [loading, setLoading] = useState(true);
  const [statsLoading, setStatsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [showGenerateModal, setShowGenerateModal] = useState(false);
  const [deletingId, setDeletingId] = useState<string | null>(null);
  const [updatingId, setUpdatingId] = useState<string | null>(null);
  const [successMsg, setSuccessMsg] = useState<string | null>(null);

  const loadBlogs = useCallback(async (p: number) => {
    setLoading(true);
    setError(null);
    try {
      const res = await fetchBlogs({ page: p, limit: LIMIT });
      setBlogs(res.blogs ?? []);
      setTotal(res.total ?? 0);
      setTotalPages(res.totalPages ?? 1);
    } catch {
      setError("Failed to load blogs.");
    } finally {
      setLoading(false);
    }
  }, []);

  const loadStats = useCallback(async () => {
    setStatsLoading(true);
    try {
      const s = await fetchBlogStats();
      setStats(s);
    } catch {
      // Stats optional
    } finally {
      setStatsLoading(false);
    }
  }, []);

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

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

  function showSuccess(msg: string) {
    setSuccessMsg(msg);
    setTimeout(() => setSuccessMsg(null), 3000);
  }

  async function handleDelete(id: string, title: string) {
    if (!confirm(`Delete "${title}"? This cannot be undone.`)) return;
    setDeletingId(id);
    try {
      await deleteBlog(id);
      setBlogs((prev) => prev.filter((b) => b.id !== id));
      setTotal((t) => t - 1);
      showSuccess("Blog deleted successfully.");
      loadStats();
    } catch {
      setError("Failed to delete blog.");
    } finally {
      setDeletingId(null);
    }
  }

  async function handleStatusChange(id: string, status: BlogStatus) {
    setUpdatingId(id);
    try {
      const updated = await updateBlog(id, { status });
      setBlogs((prev) => prev.map((b) => (b.id === id ? updated : b)));
      showSuccess("Status updated.");
      loadStats();
    } catch {
      setError("Failed to update status.");
    } finally {
      setUpdatingId(null);
    }
  }

  function handleGenerated(blog: Blog) {
    setBlogs((prev) => [blog, ...prev]);
    setTotal((t) => t + 1);
    showSuccess(`Blog "${blog.title}" generated successfully!`);
    loadStats();
  }

  return (
    <div className="max-w-[1280px] mx-auto px-4 sm:px-6 py-8 space-y-8 min-w-0">
      {/* Header */}
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 min-w-0">
        <div className="min-w-0">
          <h1 className="text-2xl font-black text-gray-900">Blog Management</h1>
          <p className="text-sm text-gray-500 mt-1 break-words">AI-generated automotive content — {total} total</p>
        </div>
        <div className="flex flex-wrap items-center gap-3">
          <button
            onClick={() => { loadBlogs(page); loadStats(); }}
            disabled={loading}
            className="flex items-center justify-center gap-2 px-4 py-2.5 min-h-[44px] rounded-2xl border border-gray-200 bg-white text-sm font-semibold text-gray-700 hover:border-blue-200 transition-all"
          >
            <RefreshCw className={cn("w-4 h-4", loading && "animate-spin")} />
            Refresh
          </button>
          <button
            onClick={() => setShowGenerateModal(true)}
            className="flex items-center justify-center gap-2 px-5 py-2.5 min-h-[44px] rounded-2xl bg-gradient-to-r from-purple-600 to-violet-500 text-white text-sm font-bold shadow-lg shadow-purple-100 hover:shadow-xl transition-all"
          >
            <Sparkles className="w-4 h-4" />
            Generate Blog
          </button>
        </div>
      </div>

      {/* Success toast */}
      <AnimatePresence>
        {successMsg && (
          <motion.div
            initial={{ opacity: 0, y: -10 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: -10 }}
            className="rounded-2xl bg-green-50 border border-green-200 p-4 flex items-start sm:items-center gap-3 text-sm text-green-700 font-medium min-w-0"
          >
            <CheckCircle2 className="w-5 h-5 shrink-0 text-green-500 mt-0.5 sm:mt-0" />
            <p className="flex-1 min-w-0 break-words">{successMsg}</p>
          </motion.div>
        )}
      </AnimatePresence>

      {error && (
        <div className="rounded-2xl bg-red-50 border border-red-200 p-4 flex items-start sm:items-center gap-3 text-sm text-red-700 min-w-0">
          <X className="w-5 h-5 shrink-0 mt-0.5 sm:mt-0" />
          <p className="flex-1 min-w-0 break-words">{error}</p>
        </div>
      )}

      {/* Stats row */}
      <section>
        <h2 className="text-xs uppercase tracking-[0.2em] text-gray-400 font-black mb-4">Content Statistics</h2>
        <div className="grid grid-cols-2 md:grid-cols-5 gap-4">
          {statsLoading ? (
            Array.from({ length: 5 }).map((_, i) => (
              <div key={i} className="rounded-[24px] bg-white border border-gray-200/60 p-5 animate-pulse">
                <div className="w-10 h-10 rounded-2xl bg-gray-100 mb-3" />
                <div className="h-7 bg-gray-100 rounded-xl w-16 mb-2" />
                <div className="h-3 bg-gray-100 rounded-lg w-24" />
              </div>
            ))
          ) : (
            <>
              <StatCard icon={FileText}   label="Total Blogs"       value={stats?.total}          color="blue"   />
              <StatCard icon={CheckCircle2}label="Published"         value={stats?.published}      color="green"  />
              <StatCard icon={Clock}       label="Drafts"            value={stats?.draft}          color="amber"  />
              <StatCard icon={Sparkles}    label="Generated Today"   value={stats?.todayGenerated} color="purple" />
              <StatCard icon={Eye}         label="Total Views"       value={stats?.totalViews?.toLocaleString()} color="orange" />
            </>
          )}
        </div>
      </section>

      {/* Category breakdown */}
      {stats?.byCategory && Object.keys(stats.byCategory).length > 0 && (
        <section>
          <h2 className="text-xs uppercase tracking-[0.2em] text-gray-400 font-black mb-4">By Category</h2>
          <div className="bg-white rounded-[24px] border border-gray-200/60 p-6 shadow-[0_4px_20px_rgba(0,0,0,0.05)]">
            <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
              {Object.entries(stats.byCategory).map(([cat, count]) => (
                <div key={cat} className="text-center p-3 rounded-2xl bg-gray-50 border border-gray-100 min-w-0">
                  <p className="text-lg font-black text-gray-900">{count}</p>
                  <p className="text-xs font-bold text-gray-500 mt-0.5 break-words">{cat}</p>
                </div>
              ))}
            </div>
          </div>
        </section>
      )}

      {/* Blogs table */}
      <section>
        <h2 className="text-xs uppercase tracking-[0.2em] text-gray-400 font-black mb-4">All Blogs</h2>
        <div className="bg-white rounded-[24px] border border-gray-200/60 shadow-[0_4px_20px_rgba(0,0,0,0.05)] overflow-hidden">
          {loading ? (
            <div className="p-8 flex items-center justify-center">
              <Loader2 className="w-8 h-8 animate-spin text-blue-500" />
            </div>
          ) : blogs.length === 0 ? (
            <div className="p-12 text-center">
              <div className="w-14 h-14 rounded-2xl bg-gray-100 flex items-center justify-center mx-auto mb-4">
                <FileText className="w-7 h-7 text-gray-400" />
              </div>
              <p className="font-black text-gray-700 mb-2">No blogs yet</p>
              <p className="text-sm text-gray-400 mb-4">Generate your first AI blog post to get started</p>
              <button
                onClick={() => setShowGenerateModal(true)}
                className="inline-flex items-center gap-2 px-4 py-2 rounded-xl bg-purple-600 text-white text-sm font-bold hover:bg-purple-700 transition-colors"
              >
                <Sparkles className="w-4 h-4" />
                Generate First Blog
              </button>
            </div>
          ) : (
            <div className="overflow-x-auto">
              <table className="w-full text-sm min-w-[520px]">
                <thead>
                  <tr className="border-b border-gray-100">
                    <th className="text-left px-3 sm:px-6 py-4 text-xs font-black uppercase tracking-wider text-gray-500">Title</th>
                    <th className="text-left px-3 sm:px-4 py-4 text-xs font-black uppercase tracking-wider text-gray-500 hidden md:table-cell">Category</th>
                    <th className="text-left px-3 sm:px-4 py-4 text-xs font-black uppercase tracking-wider text-gray-500">Status</th>
                    <th className="text-right px-3 sm:px-4 py-4 text-xs font-black uppercase tracking-wider text-gray-500 hidden lg:table-cell">Words</th>
                    <th className="text-right px-3 sm:px-4 py-4 text-xs font-black uppercase tracking-wider text-gray-500 hidden lg:table-cell">Views</th>
                    <th className="text-left px-3 sm:px-4 py-4 text-xs font-black uppercase tracking-wider text-gray-500 hidden xl:table-cell">Date</th>
                    <th className="text-right px-3 sm:px-6 py-4 text-xs font-black uppercase tracking-wider text-gray-500">Actions</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-gray-50">
                  {blogs.map((blog) => (
                    <tr key={blog.id} className="hover:bg-gray-50/50 transition-colors">
                      <td className="px-3 sm:px-6 py-4 max-w-[10rem] sm:max-w-[14rem] md:max-w-xs">
                        <div className="flex items-start gap-2 min-w-0">
                          <div className="min-w-0">
                            <p className="font-bold text-gray-900 line-clamp-1 text-sm">{blog.title}</p>
                            <p className="text-xs text-gray-400 mt-0.5 line-clamp-1">{blog.excerpt}</p>
                          </div>
                          {blog.aiGenerated && (
                            <Sparkles className="w-3.5 h-3.5 text-purple-400 shrink-0 mt-1" />
                          )}
                        </div>
                      </td>
                      <td className="px-3 sm:px-4 py-4 hidden md:table-cell">
                        <span className="text-xs font-bold text-gray-600 bg-gray-100 px-2 py-1 rounded-lg whitespace-nowrap">
                          {blog.category}
                        </span>
                      </td>
                      <td className="px-3 sm:px-4 py-4 whitespace-nowrap">
                        <StatusBadge status={blog.status} />
                      </td>
                      <td className="px-3 sm:px-4 py-4 text-right text-gray-600 font-medium hidden lg:table-cell whitespace-nowrap">
                        {blog.wordCount?.toLocaleString() ?? "—"}
                      </td>
                      <td className="px-3 sm:px-4 py-4 text-right text-gray-600 font-medium hidden lg:table-cell whitespace-nowrap">
                        {blog.views?.toLocaleString() ?? "—"}
                      </td>
                      <td className="px-3 sm:px-4 py-4 text-gray-400 text-xs hidden xl:table-cell whitespace-nowrap">
                        {formatDate(blog.publishedAt)}
                      </td>
                      <td className="px-3 sm:px-6 py-4">
                        <div className="flex items-center justify-end gap-2">
                          {/* Status change dropdown */}
                          <select
                            value={blog.status}
                            onChange={(e) => handleStatusChange(blog.id, e.target.value as BlogStatus)}
                            disabled={updatingId === blog.id}
                            className="text-xs font-bold bg-gray-50 border border-gray-200 rounded-xl px-2 py-2 min-h-[36px] focus:outline-none focus:ring-2 focus:ring-blue-500 cursor-pointer"
                          >
                            <option value="published">Published</option>
                            <option value="draft">Draft</option>
                            <option value="archived">Archived</option>
                          </select>
                          {/* Delete */}
                          <button
                            onClick={() => handleDelete(blog.id, blog.title)}
                            disabled={deletingId === blog.id}
                            className="p-2.5 rounded-xl text-red-400 hover:text-red-600 hover:bg-red-50 transition-all disabled:opacity-50 shrink-0"
                            title="Delete blog"
                            aria-label="Delete blog"
                          >
                            {deletingId === blog.id ? (
                              <Loader2 className="w-4 h-4 animate-spin" />
                            ) : (
                              <Trash2 className="w-4 h-4" />
                            )}
                          </button>
                        </div>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>
      </section>

      {/* Pagination */}
      {!loading && totalPages > 1 && (
        <div className="flex items-center justify-center gap-3 flex-wrap pb-[env(safe-area-inset-bottom,0px)]">
          <button
            onClick={() => setPage((p) => Math.max(1, p - 1))}
            disabled={page === 1}
            className="p-2.5 min-h-[44px] min-w-[44px] flex items-center justify-center 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"
            aria-label="Previous page"
          >
            <ChevronLeft className="w-5 h-5" />
          </button>
          <span className="text-sm font-bold text-gray-700 whitespace-nowrap">
            Page {page} of {totalPages}
          </span>
          <button
            onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
            disabled={page === totalPages}
            className="p-2.5 min-h-[44px] min-w-[44px] flex items-center justify-center 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"
            aria-label="Next page"
          >
            <ChevronRight className="w-5 h-5" />
          </button>
        </div>
      )}

      {/* Generate modal */}
      <AnimatePresence>
        {showGenerateModal && (
          <GenerateModal
            onClose={() => setShowGenerateModal(false)}
            onSuccess={handleGenerated}
          />
        )}
      </AnimatePresence>
    </div>
  );
}
