'use client';

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

export default function AdminPostDetail() {
  const params = useParams();
  const router = useRouter();
  const [post, setPost] = useState<any>(null);
  const [loading, setLoading] = useState(true);

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

  async function load() {
    try {
      const token = localStorage.getItem('adminToken');
      const res = await fetch(`${API_BASE}/admin/posts/${params.id}`, {
        headers: { Authorization: `Bearer ${token}` },
      });
      if (res.ok) setPost(await res.json());
    } catch {}
    setLoading(false);
  }

  async function updateStatus(status: string) {
    try {
      const token = localStorage.getItem('adminToken');
      await fetch(`${API_BASE}/admin/posts/${params.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() {
    if (!confirm('确定删除此帖子？')) return;
    try {
      const token = localStorage.getItem('adminToken');
      await fetch(`${API_BASE}/admin/posts/${params.id}`, {
        method: 'DELETE',
        headers: { Authorization: `Bearer ${token}` },
      });
      toast.success('已删除');
      router.push('/admin/posts');
    } catch { toast.error('删除失败'); }
  }

  if (loading) return <div className="p-6 space-y-4"><Skeleton className="h-8 w-48" /><Skeleton className="h-40 w-full" /></div>;
  if (!post) return <div className="p-6 text-muted-foreground">帖子不存在</div>;

  return (
    <div className="p-6 max-w-3xl">
      <div className="flex items-center justify-between mb-6">
        <h1 className="text-2xl font-bold text-foreground">帖子详情</h1>
        <div className="flex gap-2">
          {post.status === 'PUBLISHED' ? (
            <button onClick={() => updateStatus('HIDDEN')}
              className="px-3 py-1.5 rounded-lg bg-orange-500 text-white text-sm hover:bg-orange-600">隐藏</button>
          ) : (
            <button onClick={() => updateStatus('PUBLISHED')}
              className="px-3 py-1.5 rounded-lg bg-green-500 text-white text-sm hover:bg-green-600">发布</button>
          )}
          <button onClick={del}
            className="px-3 py-1.5 rounded-lg bg-red-500 text-white text-sm hover:bg-red-600">删除</button>
        </div>
      </div>

      <div className="bg-card rounded-xl border border-border p-6 space-y-4">
        <div>
          <div className="text-xs text-muted-foreground mb-1">
            作者：{post.user?.nickname || '匿名'} · 
            {new Date(post.createdAt).toLocaleString('zh-CN')} · 
            👁 {post.viewCount} · 💬 {post._count?.comments || 0} · ❤️ {post._count?.likes || 0}
          </div>
          <h2 className="text-xl font-bold text-foreground">{post.title}</h2>
        </div>
        <div className="text-sm text-foreground leading-relaxed whitespace-pre-wrap">{post.content}</div>
      </div>

      <button onClick={() => router.back()}
        className="mt-4 text-sm text-muted-foreground hover:text-foreground">&larr; 返回列表</button>
    </div>
  );
}
