<template>
    <div>
        <h1>Управление пользователями</h1>
        <div v-if="isLoading">Загрузка...</div>
        <table v-else>
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Username</th>
                    <th>Email</th>
                    <th>Роль</th>
                    <th>Действия</th>
                </tr>
            </thead>
            <tbody>
                <tr v-for="user in users" :key="user.uuid">
                    <td>{{ user.id }}</td>
                    <td>{{ user.username }}</td>
                    <td>{{ user.email }}</td>
                    <td>
                        <select v-model="user.role" @change="updateRole(user)">
                            <option value="user">user</option>
                            <option value="admin">admin</option>
                        </select>
                    </td>
                    <td><button @click="updateRole(user)">Сохранить</button></td>
                </tr>
            </tbody>
        </table>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import apiClient from "@/api/axios";

interface User {
    id: number;
    uuid: string;
    username: string;
    email: string;
    role: string;
}

const users = ref<User[]>([]);
const isLoading = ref(true);

const fetchUsers = async () => {
    isLoading.value = true;
    try {
        const response = await apiClient.get<User[]>("/admin/users");
        users.value = response.data;
    } catch (error) {
        console.error("Failed to fetch users:", error);
    } finally {
        isLoading.value = false;
    }
};

const updateRole = async (user: User) => {
    try {
        await apiClient.patch(`/admin/users/${user.id}/role`, { role: user.role });
        alert(`Роль для ${user.username} обновлена.`);
    } catch (error) {
        console.error("Failed to update role:", error);
        alert("Ошибка при обновлении роли.");
        fetchUsers();
    }
};

onMounted(fetchUsers);
</script>

<style scoped>
table {
    width: 100%;
    border-collapse: collapse;
}
th,
td {
    border: 1px solid #ddd;
    padding: 8px;
    text-align: left;
}
th {
    background-color: #f2f2f2;
}
</style>
