'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 Prompt {
  id: number;
  title: string;
  status: string;
  viewCount: number;
  likeCount: number;
  category?: { name: string };
}

export default function AdminPrompts() {
  const router = useRouter();
  const [prompts, setPrompts] = useState<Prompt[]>([]);
  const [loading, setLoading] = useState(true);

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

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

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

          {prompts.length === 0 && (
            <div className="text-center py-20 text-muted-foreground">
              暂无提示词数据
            </div>
          )}
        </div>
      </div>
    </>
  );
}
