'use client';

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

export default function EditModel() {
  const router = useRouter();
  const params = useParams();
  const [form, setForm] = useState<any>(null);
  const [loading, setLoading] = useState(true);

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

  async function load() {
    try {
      const token = localStorage.getItem('adminToken');
      const res = await fetch(`${API_BASE}/admin/models/${params.id}`, {
        headers: { Authorization: `Bearer ${token}` },
      });
      if (res.ok) {
        const data = await res.json();
        setForm({
          name: data.name, provider: data.provider, description: data.description || '',
          capabilities: data.capabilities || '', contextWindow: data.contextWindow || 4096,
          maxTokens: data.maxTokens || 2048, pricing: data.pricing || '',
          isFree: data.isFree ?? true, isFeatured: data.isFeatured ?? false,
          icon: data.icon || '', sortOrder: data.sortOrder || 0, status: data.status || 'ACTIVE',
        });
      }
    } catch {}
    setLoading(false);
  }

  async function submit(e: React.FormEvent) {
    e.preventDefault();
    try {
      const token = localStorage.getItem('adminToken');
      const res = await fetch(`${API_BASE}/admin/models/${params.id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
        body: JSON.stringify({ ...form, contextWindow: Number(form.contextWindow), maxTokens: Number(form.maxTokens), sortOrder: Number(form.sortOrder) }),
      });
      if (res.ok) {
        toast.success('更新成功');
        router.push('/admin/models');
      } else {
        const err = await res.json();
        toast.error(err.message || '更新失败');
      }
    } catch { toast.error('网络错误'); }
  }

  if (loading) return <div className="p-6 space-y-4"><Skeleton className="h-8 w-48" /><Skeleton className="h-10 w-full" /><Skeleton className="h-10 w-full" /></div>;
  if (!form) return <div className="p-6 text-muted-foreground">模型不存在</div>;

  return (
    <div className="p-6 max-w-2xl">
      <h1 className="text-2xl font-bold text-foreground mb-6">编辑模型</h1>
      <form onSubmit={submit} className="space-y-4">
        <div className="grid grid-cols-2 gap-4">
          <div>
            <label className="block text-sm font-medium text-foreground mb-1">名称 *</label>
            <input className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm" required
              value={form.name} onChange={e => setForm({ ...form, name: e.target.value })} />
          </div>
          <div>
            <label className="block text-sm font-medium text-foreground mb-1">提供商 *</label>
            <input className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm" required
              value={form.provider} onChange={e => setForm({ ...form, provider: e.target.value })} />
          </div>
        </div>
        <div>
          <label className="block text-sm font-medium text-foreground mb-1">描述</label>
          <textarea className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm" rows={3}
            value={form.description} onChange={e => setForm({ ...form, description: e.target.value })} />
        </div>
        <div>
          <label className="block text-sm font-medium text-foreground mb-1">能力标签</label>
          <input className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm"
            value={form.capabilities} onChange={e => setForm({ ...form, capabilities: e.target.value })} />
        </div>
        <div className="grid grid-cols-3 gap-4">
          <div>
            <label className="block text-sm font-medium text-foreground mb-1">上下文窗口</label>
            <input type="number" className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm"
              value={form.contextWindow} onChange={e => setForm({ ...form, contextWindow: Number(e.target.value) })} />
          </div>
          <div>
            <label className="block text-sm font-medium text-foreground mb-1">Max Tokens</label>
            <input type="number" className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm"
              value={form.maxTokens} onChange={e => setForm({ ...form, maxTokens: Number(e.target.value) })} />
          </div>
          <div>
            <label className="block text-sm font-medium text-foreground mb-1">排序</label>
            <input type="number" className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm"
              value={form.sortOrder} onChange={e => setForm({ ...form, sortOrder: Number(e.target.value) })} />
          </div>
        </div>
        <div>
          <label className="block text-sm font-medium text-foreground mb-1">图标 Emoji</label>
          <input className="w-full rounded-lg border border-border bg-background px-3 py-2 text-sm"
            value={form.icon} onChange={e => setForm({ ...form, icon: e.target.value })} />
        </div>
        <div className="flex items-center gap-6">
          <label className="flex items-center gap-2 text-sm">
            <input type="checkbox" checked={form.isFree}
              onChange={e => setForm({ ...form, isFree: e.target.checked })} />
            免费
          </label>
          <label className="flex items-center gap-2 text-sm">
            <input type="checkbox" checked={form.isFeatured}
              onChange={e => setForm({ ...form, isFeatured: e.target.checked })} />
            推荐展示
          </label>
        </div>
        <div className="flex gap-3 pt-2">
          <button type="submit" className="rounded-lg bg-primary text-primary-foreground px-6 py-2 text-sm font-medium hover:bg-primary/90">保存</button>
          <button type="button" onClick={() => router.back()} className="rounded-lg border border-border px-6 py-2 text-sm font-medium hover:bg-accent">取消</button>
        </div>
      </form>
    </div>
  );
}
