import { useEffect, useState } from "react";
import { getAllUsers, updateRole } from "../api/users";
import { ROLES } from "../constants/roles";

export default function AdminPanel() {
  const [users, setUsers] = useState([]);

  async function loadUsers() {
    const allUsers = await getAllUsers();
    console.log(allUsers);
    setUsers(allUsers.data);
  }

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

  const changeRole = async (id, role) => {
    const updated = await updateRole(id, role);
    if (updated.status !== 200) return;
    loadUsers();
  }

  return (
    <div>
      <h1>Admin Panel</h1>
      {users.map((user) => (
        <div key={user.id}>
          <strong>{user.username}</strong> - {user.role}
          <select onChange={(e) => changeRole(user.id, e.target.value)} value={user.role}>
            <option value={ROLES.VIEWER}>Viewer</option>
            <option value={ROLES.EDITOR}>Editor</option>
            <option value={ROLES.ADMIN}>Admin</option>
          </select>
        </div>
      ))
      }
    </div >
  )
}