'use client';

import { useEffect, useState } from 'react';
import { useParams, useRouter } from 'next/navigation';
import Link from 'next/link';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Card } from '@/components/ui/card';
import { Skeleton } from '@/components/ui/skeleton';
import { API_BASE } from '@/lib/config';

export default function EditToolPage() {
  const params = useParams();
  const router = useRouter();
  const [form, setForm] = useState({ name: '', description: '', url: '', icon: '', affiliateLink: '', tags: '' });
  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState('');

  useEffect(() => { loadTool(); }, [params.id]);

  function token() { return localStorage.getItem('adminToken'); }
  function authHeaders(): Record<string, string> {
    const t = token();
    return { 'Content-Type': 'application/json', ...(t ? { Authorization: `Bearer ${t}` } : {}) };
  }

  async function loadTool() {
    try {
      const res = await fetch(`${API_BASE}/admin/tools/${params.id}`, { headers: authHeaders() });
      if (res.ok) {
        const tool = await res.json();
        setForm({
          name: tool.name || '',
          description: tool.description || '',
          url: tool.url || '',
          icon: tool.icon || '',
          affiliateLink: tool.affiliateLink || '',
          tags: tool.tags || '',
        });
      } else {
        setError('加载工具信息失败');
      }
    } catch {
      setError('网络错误');
    }
    setLoading(false);
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    if (!form.name.trim() || !form.url.trim()) return;
    setSubmitting(true);
    setError('');
    try {
      const res = await fetch(`${API_BASE}/admin/tools/${params.id}`, {
        method: 'PUT',
        headers: authHeaders(),
        body: JSON.stringify(form),
      });
      if (res.ok) {
        router.push('/admin/tools');
      } else {
        const data = await res.json().catch(() => ({}));
        setError(data.message || '保存失败');
        setSubmitting(false);
      }
    } catch {
      setError('网络错误');
      setSubmitting(false);
    }
  }

  if (loading) return (
    <div className="p-6">
      <Skeleton className="h-8 w-48 mb-4" />
      <Skeleton className="h-64 w-full max-w-2xl" />
    </div>
  );

  return (
    <>
      <div className="border-b border-border bg-card px-4 py-4">
        <h1 className="text-2xl font-bold text-foreground">编辑工具</h1>
      </div>
      <div className="max-w-2xl mx-auto p-6">
        <Card className="p-6">
          <form onSubmit={handleSubmit} className="space-y-4">
            {error && (
              <div className="p-3 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg text-sm text-red-700 dark:text-red-400">
                {error}
              </div>
            )}
            <div>
              <label className="block text-sm font-medium text-foreground mb-1">名称</label>
              <Input value={form.name} onChange={e => setForm(f => ({ ...f, name: e.target.value }))} placeholder="工具名称" required />
            </div>
            <div>
              <label className="block text-sm font-medium text-foreground mb-1">描述</label>
              <textarea value={form.description} onChange={e => setForm(f => ({ ...f, description: e.target.value }))}
                rows={3} className="w-full px-3 py-2 bg-background border border-input rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-ring"
                placeholder="工具简介" />
            </div>
            <div>
              <label className="block text-sm font-medium text-foreground mb-1">链接</label>
              <Input value={form.url} onChange={e => setForm(f => ({ ...f, url: e.target.value }))} placeholder="https://..." required />
            </div>
            <div>
              <label className="block text-sm font-medium text-foreground mb-1">图标链接</label>
              <Input value={form.icon} onChange={e => setForm(f => ({ ...f, icon: e.target.value }))} placeholder="https://..." />
            </div>
            <div>
              <label className="block text-sm font-medium text-foreground mb-1">
                返佣链接 <span className="text-muted-foreground font-normal">(可选)</span>
              </label>
              <Input value={form.affiliateLink} onChange={e => setForm(f => ({ ...f, affiliateLink: e.target.value }))} placeholder="https://..." />
              <p className="text-xs text-muted-foreground mt-1">通过此链接跳转可获得返佣收入</p>
            </div>
            <div>
              <label className="block text-sm font-medium text-foreground mb-1">标签</label>
              <Input value={form.tags} onChange={e => setForm(f => ({ ...f, tags: e.target.value }))} placeholder="AI,工具,效率" />
            </div>
            <div className="flex gap-2 pt-2">
              <Button type="submit" disabled={submitting || !form.name.trim() || !form.url.trim()}>
                {submitting ? '保存中...' : '保存'}
              </Button>
              <Link href="/admin/tools"><Button type="button" variant="outline">取消</Button></Link>
            </div>
          </form>
        </Card>
      </div>
    </>
  );
}
