import { useEffect, useState } from "react";
import { getAllUsers, updateRole } from "../api/users";
import UserRoleCard from "../components/common/UserRoleCard";
import "../styles/UserRoleCard.css";
import "../styles/pages/AdminPanel.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 className="p-4" style={{ minHeight: '100vh' }}>
      <div className="card" style={{ maxWidth: '800px', margin: '0 auto' }}>
        <h1 className="text-center text-3xl font-bold mb-4">Admin Panel</h1>
        <div className="mt-4">
          {users.map((user) => (
            <UserRoleCard
              key={user.id}
              user={user}
              onRoleChange={changeRole}
            />
          ))}
        </div>
      </div>
    </div>
  )
}