'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 Course {
  id: number;
  title: string;
  isFree: boolean;
  status: string;
  category?: { name: string };
  createdAt: string;
}

export default function AdminCourses() {
  const router = useRouter();
  const [courses, setCourses] = useState<Course[]>([]);
  const [loading, setLoading] = useState(true);

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

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

  async function toggleStatus(id: number, currentStatus: string) {
    try {
      const token = localStorage.getItem('adminToken');
      await fetch(`${API_BASE}/admin/courses/${id}/status`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${token}`,
        },
        body: JSON.stringify({ status: currentStatus === 'PUBLISHED' ? 'DRAFT' : 'PUBLISHED' }),
      });
      loadCourses();
    } 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="border-b border-border bg-card px-4 py-4">
        <div className="flex items-center justify-between">
          <h1 className="text-2xl font-bold text-foreground">课程管理</h1>
          <Link href="/admin/courses/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">
              {courses.map(course => (
                <tr key={course.id} className="hover:bg-accent/50">
                  <td className="px-6 py-4 text-sm text-foreground">{course.id}</td>
                  <td className="px-6 py-4">
                    <div className="text-sm font-medium text-foreground">{course.title}</div>
                  </td>
                  <td className="px-6 py-4 text-sm text-muted-foreground">{course.category?.name || '-'}</td>
                  <td className="px-6 py-4">
                    <span className={`px-2 py-1 text-xs rounded-full ${
                      course.isFree ? 'bg-green-100 dark:bg-green-900/30 text-green-700 dark:text-green-400' : 'bg-orange-100 dark:bg-orange-900/30 text-orange-700 dark:text-orange-400'
                    }`}>
                      {course.isFree ? '免费' : '付费'}
                    </span>
                  </td>
                  <td className="px-6 py-4">
                    <span className={`px-2 py-1 text-xs rounded-full ${
                      course.status === 'PUBLISHED' ? 'bg-green-100 dark:bg-green-900/30 text-green-700 dark:text-green-400' : 'bg-yellow-100 dark:bg-yellow-900/30 text-yellow-700 dark:text-yellow-400'
                    }`}>
                      {course.status}
                    </span>
                  </td>
                  <td className="px-6 py-4 text-sm text-muted-foreground">
                    {new Date(course.createdAt).toLocaleDateString()}
                  </td>
                  <td className="px-6 py-4">
                    <div className="flex gap-2">
                      <Link href={`/admin/courses/${course.id}`} className="text-xs text-brand-600 hover:underline">
                        编辑
                      </Link>
                      <button
                        onClick={() => toggleStatus(course.id, course.status)}
                        className={`text-xs transition-colors ${
                          course.status === 'PUBLISHED' 
                            ? 'text-red-600 hover:text-red-800' 
                            : 'text-green-600 hover:text-green-800'
                        }`}
                      >
                        {course.status === 'PUBLISHED' ? '下架' : '发布'}
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>

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