import { useEffect, useState } from 'react';
import api from '../../api/client';

export default function AdminUsers() {
  const [data, setData]     = useState({ users: [], total: 0, pages: 1 });
  const [page, setPage]     = useState(1);
  const [q, setQ]           = useState('');
  const [loading, setLoading] = useState(true);

  function load() {
    setLoading(true);
    const params = new URLSearchParams({ page, limit: 30 });
    if (q) params.set('q', q);
    api.get(`/admin/users?${params}`)
      .then(r => setData(r.data))
      .catch(() => {})
      .finally(() => setLoading(false));
  }

  useEffect(() => { load(); }, [page]);

  async function toggleActive(userId) {
    await api.put(`/admin/users/${userId}/toggle`);
    load();
  }

  async function changeRole(userId, role) {
    if (!confirm(`역할을 "${role}"로 변경하시겠습니까?`)) return;
    await api.put(`/admin/users/${userId}/role`, { role });
    load();
  }

  return (
    <div className="container page">
      <h2 style={{ marginBottom: 20 }}>사용자 관리</h2>
      <div style={{ display: 'flex', gap: 8, marginBottom: 20 }}>
        <input placeholder="이메일 또는 닉네임 검색" value={q}
          onChange={e => setQ(e.target.value)}
          onKeyDown={e => { if (e.key === 'Enter') { setPage(1); load(); } }}
          style={{ maxWidth: 280 }} />
        <button className="btn btn-outline" onClick={() => { setPage(1); load(); }}>검색</button>
      </div>

      {loading ? <div className="spinner" /> : (
        <>
          <div className="table-wrap">
            <table>
              <thead>
                <tr><th>이메일</th><th>닉네임</th><th>역할</th><th>상태</th><th>가입일</th><th>최근 로그인</th><th>역할 변경</th><th></th></tr>
              </thead>
              <tbody>
                {data.users.map(u => (
                  <tr key={u.id}>
                    <td style={{ fontSize: 12 }}>{u.email}</td>
                    <td>{u.nickname}</td>
                    <td>
                      <span className={`badge badge-${u.role === 'admin' ? 'approved' : u.role === 'seller' ? 'pending' : 'draft'}`}>
                        {u.role}
                      </span>
                    </td>
                    <td>
                      <span style={{ color: u.isActive ? 'var(--success)' : 'var(--danger)', fontSize: 12 }}>
                        {u.isActive ? '활성' : '비활성'}
                      </span>
                    </td>
                    <td className="text-muted" style={{ fontSize: 12 }}>{new Date(u.createdAt).toLocaleDateString('ko-KR')}</td>
                    <td className="text-muted" style={{ fontSize: 12 }}>
                      {u.lastLoginAt ? new Date(u.lastLoginAt).toLocaleDateString('ko-KR') : '-'}
                    </td>
                    <td>
                      <select defaultValue={u.role} onChange={e => changeRole(u.id, e.target.value)}
                        style={{ width: 90, padding: '4px 8px', fontSize: 12 }}>
                        <option value="buyer">buyer</option>
                        <option value="seller">seller</option>
                        <option value="admin">admin</option>
                      </select>
                    </td>
                    <td>
                      {u.role !== 'admin' && (
                        <button className={`btn btn-sm ${u.isActive ? 'btn-danger' : 'btn-success'}`}
                          onClick={() => toggleActive(u.id)}>
                          {u.isActive ? '비활성화' : '활성화'}
                        </button>
                      )}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
          {data.pages > 1 && (
            <div className="pagination">
              <button disabled={page <= 1} onClick={() => setPage(p => p - 1)}>이전</button>
              {Array.from({ length: data.pages }, (_, i) => (
                <button key={i + 1} className={page === i + 1 ? 'active' : ''} onClick={() => setPage(i + 1)}>{i + 1}</button>
              ))}
              <button disabled={page >= data.pages} onClick={() => setPage(p => p + 1)}>다음</button>
            </div>
          )}
        </>
      )}
    </div>
  );
}
