import { useEffect, useState } from "react";
import { getAllUsers, updateRole } from "../api/users";
import UserRoleCard from "../components/common/UserRoleCard";
import "../styles/UserRoleCard.css";

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

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

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

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

  return (
    <div style={{ padding: "2rem" }}>
      <h1>Admin Panel</h1>
      <div style={{ marginTop: "2rem" }}>
        {users.map((user) => (
          <UserRoleCard
            key={user.id}
            user={user}
            onRoleChange={changeRole}
          />
        ))}
      </div>
    </div>
  )
}