'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 EditContentPage() {
  const params = useParams();
  const router = useRouter();
  const [form, setForm] = useState({ title: '', summary: '', content: '', cover: '', contentType: 'article' });
  const [loading, setLoading] = useState(true);
  const [submitting, setSubmitting] = useState(false);

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

  const base = API_BASE;
  function token() { return localStorage.getItem('adminToken'); }
  function headers() {
    const t = token();
    return { 'Content-Type': 'application/json', ...(t ? { Authorization: `Bearer ${t}` } : {}) };
  }

  async function loadContent() {
    try {
      const res = await fetch(`${base}/contents/${params.id}`, { headers: headers() });
      if (res.ok) {
        const data = await res.json();
        setForm({ title: data.title || '', summary: data.summary || '', content: data.content || '', cover: data.cover || '', contentType: data.contentType || 'article' });
      }
    } catch {}
    setLoading(false);
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    if (!form.title.trim() || !form.content.trim()) return;
    setSubmitting(true);
    try {
      const res = await fetch(`${base}/contents/${params.id}`, {
        method: 'PUT', headers: headers(), body: JSON.stringify(form),
      });
      if (res.ok) router.push('/admin/contents');
    } catch {}
    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">
            <div>
              <label className="block text-sm font-medium text-foreground mb-1">标题</label>
              <Input value={form.title} onChange={e => setForm(f => ({ ...f, title: e.target.value }))} required />
            </div>
            <div>
              <label className="block text-sm font-medium text-foreground mb-1">摘要</label>
              <Input value={form.summary} onChange={e => setForm(f => ({ ...f, summary: e.target.value }))} />
            </div>
            <div>
              <label className="block text-sm font-medium text-foreground mb-1">内容</label>
              <textarea value={form.content} onChange={e => setForm(f => ({ ...f, content: e.target.value }))}
                rows={8} 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" required />
            </div>
            <div>
              <label className="block text-sm font-medium text-foreground mb-1">封面链接</label>
              <Input value={form.cover} onChange={e => setForm(f => ({ ...f, cover: e.target.value }))} />
            </div>
            <div>
              <label className="block text-sm font-medium text-foreground mb-1">类型</label>
              <select value={form.contentType} onChange={e => setForm(f => ({ ...f, contentType: e.target.value }))}
                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">
                <option value="article">文章</option>
                <option value="news">资讯</option>
                <option value="tutorial">教程</option>
              </select>
            </div>
            <div className="flex gap-2 pt-2">
              <Button type="submit" disabled={submitting || !form.title.trim() || !form.content.trim()}>
                {submitting ? '保存中...' : '保存'}
              </Button>
              <Link href="/admin/contents"><Button type="button" variant="outline">取消</Button></Link>
            </div>
          </form>
        </Card>
      </div>
    </>
  );
}
