'use client';

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

interface User {
  id: number;
  phone: string;
  nickname: string;
  email: string;
  status: string;
  memberPlan: string;
  createdAt: string;
}

export default function UsersPage() {
  const [users, setUsers] = useState<User[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState('');
  const [showForm, setShowForm] = useState(false);
  const [form, setForm] = useState({ nickname: '', phone: '', email: '', password: '' });
  const [editId, setEditId] = useState<number | null>(null);

  useEffect(() => { loadUsers(); }, [search]);

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

  async function createUser() {
    if (!form.phone || !form.password) return alert('手机号和密码必填');
    const token = localStorage.getItem('adminToken');
    await fetch(`${API_BASE}/admin/users`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
      body: JSON.stringify(form),
    });
    setShowForm(false);
    setForm({ nickname: '', phone: '', email: '', password: '' });
    loadUsers();
  }

  async function updateUser() {
    if (!editId) return;
    const token = localStorage.getItem('adminToken');
    await fetch(`${API_BASE}/admin/users/${editId}`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
      body: JSON.stringify({ nickname: form.nickname, email: form.email }),
    });
    setEditId(null);
    setShowForm(false);
    setForm({ nickname: '', phone: '', email: '', password: '' });
    loadUsers();
  }

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

  async function toggleStatus(id: number, currentStatus: string) {
    const token = localStorage.getItem('adminToken');
    const newStatus = currentStatus === 'ACTIVE' ? 'BANNED' : 'ACTIVE';
    await fetch(`${API_BASE}/admin/users/${id}`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
      body: JSON.stringify({ status: newStatus }),
    });
    loadUsers();
  }

  function openEdit(user: User) {
    setEditId(user.id);
    setForm({ nickname: user.nickname || '', phone: user.phone || '', email: user.email || '', password: '' });
    setShowForm(true);
  }

  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={() => { setEditId(null); setForm({ nickname: '', phone: '', email: '', password: '' }); setShowForm(true); }}
          className="px-4 py-2 bg-brand-600 text-white rounded-lg">
          新增用户
        </button>
      </div>

      <div className="mb-4">
        <input type="text" value={search} onChange={e => setSearch(e.target.value)}
          placeholder="搜索用户名或手机号..."
          className="px-4 py-2 border border-border rounded-lg bg-background text-foreground w-64" />
      </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">手机号 {editId ? '(不可修改)' : '*'}</label>
              <input type="text" value={form.phone} onChange={e => setForm({...form, phone: e.target.value})}
                disabled={!!editId}
                className="w-full px-3 py-2 border border-border rounded-lg bg-background text-foreground disabled:opacity-50" />
            </div>
            <div>
              <label className="text-sm text-muted-foreground">昵称</label>
              <input type="text" value={form.nickname} onChange={e => setForm({...form, nickname: 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="email" value={form.email} onChange={e => setForm({...form, email: e.target.value})}
                className="w-full px-3 py-2 border border-border rounded-lg bg-background text-foreground" />
            </div>
            {!editId && (
              <div>
                <label className="text-sm text-muted-foreground">密码 *</label>
                <input type="password" value={form.password} onChange={e => setForm({...form, password: e.target.value})}
                  className="w-full px-3 py-2 border border-border rounded-lg bg-background text-foreground" />
              </div>
            )}
          </div>
          <div className="flex gap-2">
            <button onClick={editId ? updateUser : createUser} className="px-4 py-2 bg-brand-600 text-white rounded-lg">
              {editId ? '保存修改' : '创建用户'}
            </button>
            <button onClick={() => { setShowForm(false); setEditId(null); }} className="px-4 py-2 bg-muted text-muted-foreground rounded-lg">
              取消
            </button>
          </div>
        </div>
      )}

      <div className="bg-card border border-border rounded-xl overflow-hidden">
        <table className="w-full">
          <thead className="bg-muted/50">
            <tr>
              <th className="px-4 py-3 text-left text-sm text-muted-foreground">ID</th>
              <th className="px-4 py-3 text-left text-sm text-muted-foreground">手机号</th>
              <th className="px-4 py-3 text-left text-sm text-muted-foreground">昵称</th>
              <th className="px-4 py-3 text-left text-sm text-muted-foreground">邮箱</th>
              <th className="px-4 py-3 text-left text-sm text-muted-foreground">状态</th>
              <th className="px-4 py-3 text-left text-sm text-muted-foreground">会员</th>
              <th className="px-4 py-3 text-left text-sm text-muted-foreground">注册时间</th>
              <th className="px-4 py-3 text-left text-sm text-muted-foreground">操作</th>
            </tr>
          </thead>
          <tbody>
            {users.map(user => (
              <tr key={user.id} className="border-t border-border">
                <td className="px-4 py-3 text-sm">{user.id}</td>
                <td className="px-4 py-3 text-sm">{user.phone || '-'}</td>
                <td className="px-4 py-3 text-sm">{user.nickname || '-'}</td>
                <td className="px-4 py-3 text-sm">{user.email || '-'}</td>
                <td className="px-4 py-3">
                  <span className={`text-xs px-2 py-1 rounded-full ${user.status === 'ACTIVE' ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'}`}>
                    {user.status === 'ACTIVE' ? '正常' : '禁用'}
                  </span>
                </td>
                <td className="px-4 py-3 text-sm">{user.memberPlan || 'FREE'}</td>
                <td className="px-4 py-3 text-sm text-muted-foreground">{user.createdAt?.slice(0, 10)}</td>
                <td className="px-4 py-3">
                  <button onClick={() => openEdit(user)} className="text-brand-600 hover:underline text-sm mr-3">编辑</button>
                  <button onClick={() => toggleStatus(user.id, user.status)} className="text-orange-600 hover:underline text-sm mr-3">
                    {user.status === 'ACTIVE' ? '禁用' : '启用'}
                  </button>
                  <button onClick={() => deleteUser(user.id)} className="text-red-500 hover:underline text-sm">删除</button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}