'use client';

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

interface Notification {
  id: number;
  title: string;
  content: string;
  type: string;
  target: string;
  status: string;
  sentAt: string;
}

export default function NotificationsPage() {
  const [notifications, setNotifications] = useState<Notification[]>([]);
  const [loading, setLoading] = useState(true);
  const [showForm, setShowForm] = useState(false);
  const [form, setForm] = useState({ title: '', content: '', type: 'system', target: 'all' });

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

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

  async function sendNotification() {
    if (!form.title || !form.content) return toast.error('请填写标题和内容');
    const token = localStorage.getItem('adminToken');
    await fetch(`${API_BASE}/admin/notifications`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
      body: JSON.stringify({ ...form, status: 'SENT' }),
    });
    setShowForm(false);
    setForm({ title: '', content: '', type: 'system', target: 'all' });
    loadNotifications();
  }

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

  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">推送管理</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 ? '取消' : '发送推送'}
        </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">类型</label>
              <select value={form.type} onChange={e => setForm({...form, type: e.target.value})}
                className="w-full px-3 py-2 border border-border rounded-lg bg-background text-foreground">
                <option value="system">系统通知</option>
                <option value="promo">促销</option>
                <option value="update">更新</option>
              </select>
            </div>
            <div>
              <label className="text-sm text-muted-foreground">发送范围</label>
              <select value={form.target} onChange={e => setForm({...form, target: e.target.value})}
                className="w-full px-3 py-2 border border-border rounded-lg bg-background text-foreground">
                <option value="all">全部用户</option>
                <option value="vip">仅会员</option>
                <option value="new">新用户</option>
              </select>
            </div>
          </div>
          <div>
            <label className="text-sm text-muted-foreground">内容 *</label>
            <textarea value={form.content} onChange={e => setForm({...form, content: e.target.value})}
              className="w-full px-3 py-2 border border-border rounded-lg bg-background text-foreground" rows={4} />
          </div>
          <button onClick={sendNotification} className="px-4 py-2 bg-brand-600 text-white rounded-lg">发送</button>
        </div>
      )}

      <div className="space-y-3">
        {notifications.length === 0 ? (
          <div className="text-center py-12 text-muted-foreground">暂无推送记录</div>
        ) : notifications.map(n => (
          <div key={n.id} className="bg-card border border-border rounded-xl p-4">
            <div className="flex items-center justify-between">
              <div>
                <div className="font-medium text-foreground">{n.title}</div>
                <div className="text-sm text-muted-foreground mt-1">{n.content}</div>
                <div className="text-xs text-muted-foreground mt-2">
                  {n.type} · {n.target} · {n.sentAt ? new Date(n.sentAt).toLocaleString() : '未发送'}
                </div>
              </div>
              <button onClick={() => deleteNotification(n.id)} className="text-red-500 hover:text-red-700">删除</button>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}