'use client';

import { useEffect, useState } from 'react';
import { API_BASE } from '@/lib/config';
import { toast } from 'sonner';

interface Banner {
  id: number;
  title: string;
  image: string;
  link: string;
  position: string;
  sortOrder: number;
  status: string;
}

export default function BannersPage() {
  const [banners, setBanners] = useState<Banner[]>([]);
  const [loading, setLoading] = useState(true);
  const [showForm, setShowForm] = useState(false);
  const [form, setForm] = useState({ title: '', image: '', link: '', position: 'home', sortOrder: 0 });

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

  async function loadBanners() {
    setLoading(true);
    try {
      const token = localStorage.getItem('adminToken');
      const res = await fetch(`${API_BASE}/admin/banners`, {
        headers: { Authorization: `Bearer ${token}` },
      });
      if (res.ok) {
        const data = await res.json();
        setBanners(data.items || []);
      }
    } catch {}
    setLoading(false);
  }

  async function createBanner() {
    if (!form.title || !form.image) return toast.error('请填写标题和图片');
    const token = localStorage.getItem('adminToken');
    await fetch(`${API_BASE}/admin/banners`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
      body: JSON.stringify({ ...form, status: 'PUBLISHED' }),
    });
    setShowForm(false);
    setForm({ title: '', image: '', link: '', position: 'home', sortOrder: 0 });
    loadBanners();
  }

  async function deleteBanner(id: number) {
    if (!confirm('确定删除？')) return;
    const token = localStorage.getItem('adminToken');
    await fetch(`${API_BASE}/admin/banners/${id}`, {
      method: 'DELETE',
      headers: { Authorization: `Bearer ${token}` },
    });
    loadBanners();
  }

  if (loading) return <div className="p-6">加载中...</div>;

  return (
    <div className="p-6">
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-2xl font-bold text-foreground">Banner 管理</h1>
          <p className="text-sm text-muted-foreground">管理首页横幅广告</p>
        </div>
        <button onClick={() => setShowForm(!showForm)} className="px-4 py-2 bg-brand-600 text-white rounded-lg">
          {showForm ? '取消' : '新建Banner'}
        </button>
      </div>

      {showForm && (
        <div className="bg-card border border-border rounded-xl p-4 mb-6 space-y-4">
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="text-sm text-muted-foreground">标题 *</label>
              <input type="text" value={form.title} onChange={e => setForm({...form, title: e.target.value})}
                className="w-full px-3 py-2 border border-border rounded-lg bg-background text-foreground" />
            </div>
            <div>
              <label className="text-sm text-muted-foreground">图片URL *</label>
              <input type="text" value={form.image} onChange={e => setForm({...form, image: e.target.value})}
                className="w-full px-3 py-2 border border-border rounded-lg bg-background text-foreground" />
            </div>
            <div>
              <label className="text-sm text-muted-foreground">跳转链接</label>
              <input type="text" value={form.link} onChange={e => setForm({...form, link: e.target.value})}
                className="w-full px-3 py-2 border border-border rounded-lg bg-background text-foreground" />
            </div>
            <div>
              <label className="text-sm text-muted-foreground">位置</label>
              <select value={form.position} onChange={e => setForm({...form, position: e.target.value})}
                className="w-full px-3 py-2 border border-border rounded-lg bg-background text-foreground">
                <option value="home">首页</option>
                <option value="skills">技能页</option>
                <option value="courses">课程页</option>
              </select>
            </div>
          </div>
          <button onClick={createBanner} className="px-4 py-2 bg-brand-600 text-white rounded-lg">保存</button>
        </div>
      )}

      <div className="space-y-3">
        {banners.length === 0 ? (
          <div className="text-center py-12 text-muted-foreground">暂无Banner</div>
        ) : banners.map(banner => (
          <div key={banner.id} className="bg-card border border-border rounded-xl p-4 flex items-center gap-4">
            <img src={banner.image} alt={banner.title} className="w-24 h-16 object-cover rounded" />
            <div className="flex-1">
              <div className="font-medium text-foreground">{banner.title}</div>
              <div className="text-sm text-muted-foreground">{banner.position} · 排序: {banner.sortOrder}</div>
            </div>
            <button onClick={() => deleteBanner(banner.id)} className="text-red-500 hover:text-red-700">删除</button>
          </div>
        ))}
      </div>
    </div>
  );
}