"use client";

import { useState, useEffect } from "react";
import { adminAPI } from "@/lib/api";
import { format } from "date-fns";
import { MessageSquare, Plus, Trash2, RefreshCw, Pencil } from "lucide-react";

interface AdminCategory {
  id: number;
  slug: string;
  name: string;
  description: string | null;
  post_count: number;
}

interface AdminPost {
  id: number;
  title: string;
  author_name: string;
  category_name: string;
  reply_count: number;
  created_at: string;
}

export default function ForumAdminPage() {
  const [tab, setTab] = useState<"categories" | "posts">("categories");
  const [categories, setCategories] = useState<AdminCategory[]>([]);
  const [posts, setPosts] = useState<AdminPost[]>([]);
  const [loading, setLoading] = useState(true);
  const [confirmDelete, setConfirmDelete] = useState<{ type: "cat" | "post"; id: number } | null>(null);

  // Category form
  const [showCatForm, setShowCatForm] = useState(false);
  const [editingCat, setEditingCat] = useState<AdminCategory | null>(null);
  const [catForm, setCatForm] = useState({ name: "", slug: "", description: "" });

  const loadCategories = () => {
    adminAPI.listForumCategories()
      .then(setCategories)
      .catch(console.error);
  };

  const loadPosts = () => {
    adminAPI.listForumPosts()
      .then(setPosts)
      .catch(console.error);
  };

  useEffect(() => {
    setLoading(true);
    Promise.all([loadCategories(), loadPosts()]).finally(() => setLoading(false));
  }, []);

  const handleSaveCategory = async () => {
    try {
      if (editingCat) {
        await adminAPI.updateForumCategory(editingCat.id, catForm);
      } else {
        await adminAPI.createForumCategory(catForm);
      }
      setShowCatForm(false);
      setEditingCat(null);
      setCatForm({ name: "", slug: "", description: "" });
      loadCategories();
    } catch (e) { console.error(e); }
  };

  const handleDeleteCategory = async (id: number) => {
    try {
      await adminAPI.deleteForumCategory(id);
      setConfirmDelete(null);
      loadCategories();
    } catch (e) { console.error(e); }
  };

  const handleDeletePost = async (id: number) => {
    try {
      await adminAPI.deleteForumPost(id);
      setConfirmDelete(null);
      loadPosts();
    } catch (e) { console.error(e); }
  };

  const startEditCat = (cat: AdminCategory) => {
    setEditingCat(cat);
    setCatForm({ name: cat.name, slug: cat.slug, description: cat.description || "" });
    setShowCatForm(true);
  };

  if (loading) {
    return <div className="text-muted-foreground text-sm py-12 text-center">加载中...</div>;
  }

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-3">
          <MessageSquare className="w-5 h-5 text-primary" />
          <h2 className="text-lg font-semibold">论坛管理</h2>
        </div>
        <div className="flex items-center gap-2">
          <button
            onClick={() => setTab("categories")}
            className={`px-3 py-1 text-sm rounded-lg transition-colors ${
              tab === "categories" ? "bg-primary text-primary-foreground" : "text-muted-foreground hover:bg-muted"
            }`}
          >
            分类管理
          </button>
          <button
            onClick={() => setTab("posts")}
            className={`px-3 py-1 text-sm rounded-lg transition-colors ${
              tab === "posts" ? "bg-primary text-primary-foreground" : "text-muted-foreground hover:bg-muted"
            }`}
          >
            帖子管理
          </button>
        </div>
      </div>

      {tab === "categories" && (
        <div className="space-y-4">
          {!showCatForm ? (
            <button
              onClick={() => { setEditingCat(null); setCatForm({ name: "", slug: "", description: "" }); setShowCatForm(true); }}
              className="flex items-center gap-1.5 text-sm text-primary hover:underline"
            >
              <Plus className="w-4 h-4" />
              新增分类
            </button>
          ) : (
            <div className="rounded-xl border p-4 space-y-3">
              <h3 className="text-sm font-medium">{editingCat ? "编辑分类" : "新增分类"}</h3>
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="text-xs text-muted-foreground">名称</label>
                  <input
                    value={catForm.name}
                    onChange={(e) => setCatForm((f) => ({ ...f, name: e.target.value }))}
                    className="w-full mt-1 px-3 py-1.5 text-sm border rounded-lg bg-background focus:outline-none focus:ring-1 focus:ring-primary"
                  />
                </div>
                <div>
                  <label className="text-xs text-muted-foreground">Slug</label>
                  <input
                    value={catForm.slug}
                    onChange={(e) => setCatForm((f) => ({ ...f, slug: e.target.value }))}
                    className="w-full mt-1 px-3 py-1.5 text-sm border rounded-lg bg-background focus:outline-none focus:ring-1 focus:ring-primary"
                  />
                </div>
                <div className="col-span-2">
                  <label className="text-xs text-muted-foreground">描述</label>
                  <input
                    value={catForm.description}
                    onChange={(e) => setCatForm((f) => ({ ...f, description: e.target.value }))}
                    className="w-full mt-1 px-3 py-1.5 text-sm border rounded-lg bg-background focus:outline-none focus:ring-1 focus:ring-primary"
                  />
                </div>
              </div>
              <div className="flex gap-2">
                <button onClick={handleSaveCategory} className="px-4 py-1.5 text-sm bg-primary text-primary-foreground rounded-lg hover:opacity-90">
                  保存
                </button>
                <button onClick={() => { setShowCatForm(false); setEditingCat(null); }} className="px-4 py-1.5 text-sm border rounded-lg hover:bg-muted">
                  取消
                </button>
              </div>
            </div>
          )}

          <div className="rounded-xl border overflow-hidden">
            <table className="w-full text-sm">
              <thead>
                <tr className="border-b bg-muted/30">
                  <th className="text-left px-4 py-3 font-medium">名称</th>
                  <th className="text-left px-4 py-3 font-medium">Slug</th>
                  <th className="text-left px-4 py-3 font-medium">描述</th>
                  <th className="text-center px-4 py-3 font-medium">帖子数</th>
                  <th className="text-center px-4 py-3 font-medium">操作</th>
                </tr>
              </thead>
              <tbody>
                {categories.map((cat) => (
                  <tr key={cat.id} className="border-b last:border-0 hover:bg-muted/20">
                    <td className="px-4 py-3 font-medium">{cat.name}</td>
                    <td className="px-4 py-3 text-muted-foreground font-mono text-xs">{cat.slug}</td>
                    <td className="px-4 py-3 text-muted-foreground text-xs max-w-40 truncate">{cat.description || "—"}</td>
                    <td className="px-4 py-3 text-center font-mono tabular-nums">{cat.post_count}</td>
                    <td className="px-4 py-3">
                      <div className="flex items-center justify-center gap-2">
                        <button onClick={() => startEditCat(cat)} className="text-muted-foreground hover:text-foreground">
                          <Pencil className="w-3.5 h-3.5" />
                        </button>
                        {confirmDelete?.type === "cat" && confirmDelete.id === cat.id ? (
                          <div className="flex items-center gap-1">
                            <button onClick={() => handleDeleteCategory(cat.id)} className="text-xs px-1.5 py-0.5 bg-destructive text-destructive-foreground rounded">确认</button>
                            <button onClick={() => setConfirmDelete(null)} className="text-xs px-1.5 py-0.5 border rounded">取消</button>
                          </div>
                        ) : (
                          <button onClick={() => setConfirmDelete({ type: "cat", id: cat.id })} className="text-red-500 hover:text-red-700">
                            <Trash2 className="w-3.5 h-3.5" />
                          </button>
                        )}
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {tab === "posts" && (
        <div className="space-y-4">
          <div className="flex items-center justify-between">
            <span className="text-sm text-muted-foreground">共 {posts.length} 个帖子</span>
            <button onClick={loadPosts} className="flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground">
              <RefreshCw className="w-3.5 h-3.5" />
              刷新
            </button>
          </div>
          <div className="rounded-xl border overflow-hidden">
            <table className="w-full text-sm">
              <thead>
                <tr className="border-b bg-muted/30">
                  <th className="text-left px-4 py-3 font-medium">标题</th>
                  <th className="text-left px-4 py-3 font-medium">作者</th>
                  <th className="text-left px-4 py-3 font-medium">分类</th>
                  <th className="text-center px-4 py-3 font-medium">回复数</th>
                  <th className="text-left px-4 py-3 font-medium">时间</th>
                  <th className="text-center px-4 py-3 font-medium">操作</th>
                </tr>
              </thead>
              <tbody>
                {posts.length === 0 ? (
                  <tr><td colSpan={6} className="px-4 py-8 text-center text-muted-foreground">暂无帖子</td></tr>
                ) : posts.map((p) => (
                  <tr key={p.id} className="border-b last:border-0 hover:bg-muted/20">
                    <td className="px-4 py-3 font-medium max-w-64 truncate">{p.title}</td>
                    <td className="px-4 py-3 text-muted-foreground">{p.author_name}</td>
                    <td className="px-4 py-3 text-muted-foreground text-xs">{p.category_name}</td>
                    <td className="px-4 py-3 text-center font-mono tabular-nums">{p.reply_count}</td>
                    <td className="px-4 py-3 text-muted-foreground text-xs">
                      {format(new Date(p.created_at), "yyyy/M/d HH:mm")}
                    </td>
                    <td className="px-4 py-3 text-center">
                      {confirmDelete?.type === "post" && confirmDelete.id === p.id ? (
                        <div className="flex items-center justify-center gap-1">
                          <button onClick={() => handleDeletePost(p.id)} className="text-xs px-2 py-1 bg-red-600 text-white rounded">确认</button>
                          <button onClick={() => setConfirmDelete(null)} className="text-xs px-2 py-1 border rounded">取消</button>
                        </div>
                      ) : (
                        <button onClick={() => setConfirmDelete({ type: "post", id: p.id })} className="text-red-500 hover:text-red-700">
                          <Trash2 className="w-4 h-4" />
                        </button>
                      )}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}
    </div>
  );
}
