'use client';

import { useEffect, useState } from 'react';
import Link from 'next/link';
import { Skeleton } from '@/components/ui/skeleton';
import { API_BASE } from '@/lib/config';
import { toast } from 'sonner';

interface Post {
  id: number;
  title: string;
  status: string;
  viewCount: number;
  createdAt: string;
  user: { id: number; nickname: string };
  _count: { comments: number; likes: number };
}

export default function AdminPosts() {
  const [items, setItems] = useState<Post[]>([]);
  const [loading, setLoading] = useState(true);
  const [statusFilter, setStatusFilter] = useState('');

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

  async function load() {
    try {
      const token = localStorage.getItem('adminToken');
      const params = new URLSearchParams({ pageSize: '100' });
      if (statusFilter) params.set('status', statusFilter);
      const res = await fetch(`${API_BASE}/admin/posts?${params}`, {
        headers: { Authorization: `Bearer ${token}` },
      });
      if (res.ok) {
        const data = await res.json();
        setItems(data.items || []);
      }
    } catch {}
    setLoading(false);
  }

  async function updateStatus(id: number, status: string) {
    try {
      const token = localStorage.getItem('adminToken');
      await fetch(`${API_BASE}/admin/posts/${id}/status`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
        body: JSON.stringify({ status }),
      });
      toast.success('状态已更新');
      load();
    } catch { toast.error('操作失败'); }
  }

  async function del(id: number) {
    if (!confirm('确定删除此帖子？此操作不可恢复。')) return;
    try {
      const token = localStorage.getItem('adminToken');
      await fetch(`${API_BASE}/admin/posts/${id}`, {
        method: 'DELETE',
        headers: { Authorization: `Bearer ${token}` },
      });
      toast.success('已删除');
      load();
    } catch { toast.error('删除失败'); }
  }

  if (loading) return (
    <div className="space-y-4 p-6">
      <Skeleton className="h-8 w-48" />
      <Skeleton className="h-10 w-full" />
      <Skeleton className="h-10 w-full" />
    </div>
  );

  return (
    <>
      <div className="border-b border-border bg-card px-4 py-4">
        <h1 className="text-2xl font-bold text-foreground">帖子管理</h1>
        <p className="text-sm text-muted-foreground">管理社区帖子</p>
      </div>

      <div className="p-6">
        <div className="flex gap-2 mb-4">
          {['', 'PUBLISHED', 'HIDDEN'].map(s => (
            <button key={s} onClick={() => setStatusFilter(s)}
              className={`px-3 py-1.5 rounded-lg text-sm font-medium transition-colors ${
                statusFilter === s ? 'bg-foreground text-background' : 'bg-muted text-muted-foreground hover:text-foreground'
              }`}>
              {s || '全部'}
            </button>
          ))}
        </div>

        <div className="bg-card rounded-xl border border-border overflow-hidden">
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b border-border bg-muted/30">
                <th className="text-left px-4 py-3 font-medium text-muted-foreground">ID</th>
                <th className="text-left px-4 py-3 font-medium text-muted-foreground">标题</th>
                <th className="text-left px-4 py-3 font-medium text-muted-foreground">作者</th>
                <th className="text-left px-4 py-3 font-medium text-muted-foreground">状态</th>
                <th className="text-left px-4 py-3 font-medium text-muted-foreground">互动</th>
                <th className="text-left px-4 py-3 font-medium text-muted-foreground">时间</th>
                <th className="text-right px-4 py-3 font-medium text-muted-foreground">操作</th>
              </tr>
            </thead>
            <tbody>
              {items.length === 0 && (
                <tr><td colSpan={7} className="text-center py-12 text-muted-foreground">暂无帖子</td></tr>
              )}
              {items.map(item => (
                <tr key={item.id} className="border-b border-border hover:bg-muted/20">
                  <td className="px-4 py-3">{item.id}</td>
                  <td className="px-4 py-3 font-medium max-w-xs truncate">{item.title}</td>
                  <td className="px-4 py-3 text-muted-foreground">{item.user?.nickname || '匿名'}</td>
                  <td className="px-4 py-3">
                    <span className={`inline-block px-2 py-0.5 rounded text-xs font-medium ${
                      item.status === 'PUBLISHED' ? 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400' :
                      item.status === 'HIDDEN' ? 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400' :
                      'bg-gray-100 text-gray-500 dark:bg-gray-800 dark:text-gray-400'
                    }`}>{item.status}</span>
                  </td>
                  <td className="px-4 py-3 text-muted-foreground">
                    💬 {item._count?.comments || 0} · ❤️ {item._count?.likes || 0} · 👁 {item.viewCount}
                  </td>
                  <td className="px-4 py-3 text-muted-foreground text-xs">
                    {new Date(item.createdAt).toLocaleDateString('zh-CN')}
                  </td>
                  <td className="px-4 py-3 text-right space-x-2">
                    <Link href={`/admin/posts/${item.id}`}
                      className="text-xs text-blue-600 hover:text-blue-700 dark:text-blue-400">详情</Link>
                    {item.status === 'PUBLISHED' ? (
                      <button onClick={() => updateStatus(item.id, 'HIDDEN')}
                        className="text-xs text-orange-600 hover:text-orange-700 dark:text-orange-400">隐藏</button>
                    ) : (
                      <button onClick={() => updateStatus(item.id, 'PUBLISHED')}
                        className="text-xs text-green-600 hover:text-green-700 dark:text-green-400">发布</button>
                    )}
                    <button onClick={() => del(item.id)}
                      className="text-xs text-red-600 hover:text-red-700 dark:text-red-400">删除</button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </>
  );
}
