'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 Tool {
  id: number;
  name: string;
  description?: string;
  category?: { name: string };
  status: string;
}

export default function AdminTools() {
  const router = useRouter();
  const [tools, setTools] = useState<Tool[]>([]);
  const [loading, setLoading] = useState(true);

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

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

  async function toggleStatus(id: number, currentStatus: string) {
    try {
      const token = localStorage.getItem('adminToken');
      await fetch(`${API_BASE}/admin/tools/${id}/status`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${token}`,
        },
        body: JSON.stringify({ status: currentStatus === 'PUBLISHED' ? 'DRAFT' : 'PUBLISHED' }),
      });
      loadTools();
    } 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/tools/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>
              </tr>
            </thead>
            <tbody className="divide-y divide-border">
              {tools.map(tool => (
                <tr key={tool.id} className="hover:bg-accent/50">
                  <td className="px-6 py-4 text-sm text-foreground">{tool.id}</td>
                  <td className="px-6 py-4">
                    <div className="text-sm font-medium text-foreground">{tool.name}</div>
                    <div className="text-xs text-muted-foreground mt-1">{tool.description?.slice(0, 50)}...</div>
                  </td>
                  <td className="px-6 py-4 text-sm text-muted-foreground">{tool.category?.name || '-'}</td>
                  <td className="px-6 py-4">
                    <span className={`px-2 py-1 text-xs rounded-full ${
                      tool.status === 'PUBLISHED' ? 'bg-green-100 text-green-700' : 'bg-yellow-100 text-yellow-700'
                    }`}>
                      {tool.status}
                    </span>
                  </td>
                  <td className="px-6 py-4">
                    <div className="flex gap-2">
                      <Link href={`/admin/tools/${tool.id}`} className="text-xs text-brand-600 hover:underline">
                        编辑
                      </Link>
                      <button
                        onClick={() => toggleStatus(tool.id, tool.status)}
                        className={`text-xs ${
                          tool.status === 'PUBLISHED' 
                            ? 'text-red-600 hover:text-red-800' 
                            : 'text-green-600 hover:text-green-800'
                        }`}
                      >
                        {tool.status === 'PUBLISHED' ? '下架' : '发布'}
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>

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