import { useState, useEffect } from 'react';
import { getUsers, updateUserRole, deleteUser } from '../../api/users';
import { useAuth } from '../../context/AuthContext';
import './AdminCommon.css';

export default function UserAdmin() {
  const [users, setUsers] = useState([]);
  const { user: me } = useAuth();

  const load = () => getUsers().then(setUsers);
  useEffect(() => { load(); }, []);

  const handleRoleToggle = async (u) => {
    const newRole = u.role === 'admin' ? 'user' : 'admin';
    if (!confirm(`${u.username}의 권한을 ${newRole}로 변경하시겠습니까?`)) return;
    await updateUserRole(u.id, newRole);
    load();
  };

  const handleDelete = async (u) => {
    if (!confirm(`${u.username} 계정을 삭제하시겠습니까?`)) return;
    await deleteUser(u.id);
    load();
  };

  return (
    <div className="admin-section">
      <h2 className="admin-section-title">유저 관리</h2>
      <ul className="admin-list">
        {users.map((u) => (
          <li key={u.id} className="admin-list-item">
            <div className="admin-list-info">
              <span className="admin-list-title">{u.username}</span>
              <span className={`admin-role-badge ${u.role}`}>{u.role}</span>
            </div>
            {u.username !== me?.username && (
              <div className="admin-list-actions">
                <button className="btn-admin-edit" onClick={() => handleRoleToggle(u)}>
                  {u.role === 'admin' ? '일반으로' : '관리자로'}
                </button>
                <button className="btn-admin-delete" onClick={() => handleDelete(u)}>삭제</button>
              </div>
            )}
          </li>
        ))}
      </ul>
    </div>
  );
}
