'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 Practice {
  id: number;
  title: string;
  description?: string;
  difficulty: string;
  category?: string;
  sortOrder: number;
  isActive: boolean;
}

export default function AdminPractices() {
  const router = useRouter();
  const [items, setItems] = useState<Practice[]>([]);
  const [loading, setLoading] = useState(true);

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

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

  async function toggleActive(id: number, current: boolean) {
    try {
      const token = localStorage.getItem('adminToken');
      await fetch(`${API_BASE}/admin/practices/${id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
        body: JSON.stringify({ isActive: !current }),
      });
      load();
    } catch {}
  }

  async function del(id: number) {
    if (!confirm('确定删除此练习？')) return;
    try {
      const token = localStorage.getItem('adminToken');
      await fetch(`${API_BASE}/admin/practices/${id}`, {
        method: 'DELETE',
        headers: { Authorization: `Bearer ${token}` },
      });
      load();
    } 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" />
    </div>
  );

  return (
    <>
      <div className="border-b border-border bg-card px-4 py-4 flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-foreground">练习管理</h1>
          <p className="text-sm text-muted-foreground">管理练习题内容</p>
        </div>
        <Link href="/admin/practices/new"
          className="rounded-lg bg-primary text-primary-foreground px-4 py-2 text-sm font-medium hover:bg-primary/90">
          新增练习
        </Link>
      </div>

      <div className="p-6">
        <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">{item.title}</td>
                  <td className="px-4 py-3">
                    <span className={`inline-block px-2 py-0.5 rounded text-xs font-medium ${
                      item.difficulty === 'BEGINNER' ? 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400' :
                      item.difficulty === 'INTERMEDIATE' ? 'bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-400' :
                      'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400'
                    }`}>
                      {item.difficulty}
                    </span>
                  </td>
                  <td className="px-4 py-3 text-muted-foreground">{item.category || '-'}</td>
                  <td className="px-4 py-3 text-muted-foreground">{item.sortOrder}</td>
                  <td className="px-4 py-3">
                    <button onClick={() => toggleActive(item.id, item.isActive)}
                      className={`text-xs px-2 py-1 rounded ${item.isActive ? 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400' : 'bg-gray-100 text-gray-500 dark:bg-gray-800 dark:text-gray-400'}`}>
                      {item.isActive ? '启用' : '禁用'}
                    </button>
                  </td>
                  <td className="px-4 py-3 text-right space-x-2">
                    <Link href={`/admin/practices/${item.id}`}
                      className="text-xs text-blue-600 hover:text-blue-700 dark:text-blue-400">编辑</Link>
                    <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>
    </>
  );
}
