'use client';

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

interface Content {
  id: number;
  title: string;
  status: string;
  viewCount: number;
  category?: { name: string };
  createdAt: string;
}

export default function AdminContents() {
  const router = useRouter();
  const [contents, setContents] = useState<Content[]>([]);
  const [loading, setLoading] = useState(true);

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

  async function loadContents() {
    try {
      const token = localStorage.getItem('adminToken');
      const res = await fetch(`${API_BASE}/contents?pageSize=50`, {
        headers: { Authorization: `Bearer ${token}` },
      });
      
      if (res.ok) {
        const data = await res.json();
        setContents(data.items || []);
      }
    } catch {}
    setLoading(false);
  }

  async function toggleStatus(id: number, currentStatus: string) {
    try {
      const token = localStorage.getItem('adminToken');
      await fetch(`${API_BASE}/admin/contents/${id}/status`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${token}`,
        },
        body: JSON.stringify({ status: currentStatus === 'PUBLISHED' ? 'DRAFT' : 'PUBLISHED' }),
      });
      loadContents();
    } catch {}
  }

  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" />
      <Skeleton className="h-10 w-3/4" />
    </div>
  );

  return (
    <>
      <div className="bg-card border-b border-border px-4 py-4">
        <div className="flex items-center justify-between">
          <h1 className="text-2xl font-bold text-foreground">内容管理</h1>
          <Link href="/admin/contents/new" className="px-4 py-2 bg-brand-600 text-white rounded-lg text-sm hover:bg-brand-700">
            新建内容
          </Link>
        </div>
      </div>

      <div className="p-6">
        <div className="bg-card rounded-xl border border-border overflow-hidden">
          <table className="w-full">
            <thead className="bg-muted/50 border-b border-border">
              <tr>
                <th className="px-6 py-3 text-left text-xs font-medium text-muted-foreground uppercase">ID</th>
                <th className="px-6 py-3 text-left text-xs font-medium text-muted-foreground uppercase">标题</th>
                <th className="px-6 py-3 text-left text-xs font-medium text-muted-foreground uppercase">分类</th>
                <th className="px-6 py-3 text-left text-xs font-medium text-muted-foreground uppercase">状态</th>
                <th className="px-6 py-3 text-left text-xs font-medium text-muted-foreground uppercase">浏览</th>
                <th className="px-6 py-3 text-left text-xs font-medium text-muted-foreground uppercase">创建时间</th>
                <th className="px-6 py-3 text-left text-xs font-medium text-muted-foreground uppercase">操作</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-border">
              {contents.map(content => (
                <tr key={content.id} className="hover:bg-accent/50">
                  <td className="px-6 py-4 text-sm text-foreground">{content.id}</td>
                  <td className="px-6 py-4">
                    <div className="text-sm font-medium text-foreground">{content.title}</div>
                  </td>
                  <td className="px-6 py-4 text-sm text-muted-foreground">{content.category?.name || '-'}</td>
                  <td className="px-6 py-4">
                    <span className={`px-2 py-1 text-xs rounded-full ${
                      content.status === 'PUBLISHED' ? 'bg-green-100 text-green-700' : 'bg-yellow-100 text-yellow-700'
                    }`}>
                      {content.status}
                    </span>
                  </td>
                  <td className="px-6 py-4 text-sm text-muted-foreground">&#128065; {content.viewCount}</td>
                  <td className="px-6 py-4 text-sm text-muted-foreground">
                    {new Date(content.createdAt).toLocaleDateString()}
                  </td>
                  <td className="px-6 py-4">
                    <div className="flex gap-2">
                      <Link href={`/admin/contents/${content.id}`} className="text-xs text-brand-600 hover:underline">
                        编辑
                      </Link>
                      <button
                        onClick={() => toggleStatus(content.id, content.status)}
                        className={`text-xs ${
                          content.status === 'PUBLISHED' 
                            ? 'text-red-600 hover:text-red-800' 
                            : 'text-green-600 hover:text-green-800'
                        }`}
                      >
                        {content.status === 'PUBLISHED' ? '下架' : '发布'}
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>

          {contents.length === 0 && (
            <div className="text-center py-20 text-muted-foreground">
              暂无内容数据
            </div>
          )}
        </div>
      </div>
    </>
  );
}
