<template>
    <div class="flex items-center justify-between">
        <h1 class="text-3xl font-bold uppercase text-primary-500">Liste des utilisateurs</h1>
        <NuxtLink
            to="/admin/user"
            class="inline-flex items-center justify-center text-xl text-white uppercase bg-primary-500 h-[50px] px-8 rounded hover:opacity-80 gap-2"
        >
            <Icon name="mdi:plus" size="28"  />
            Ajouter
        </NuxtLink>

    </div>

    <div>
        <div class="mt-6 border border-slate-200 mb-16 ">
            <div class="grid grid-cols-3 gap-4 bg-slate-100 px-4 py-3 text-sm font-semibold uppercase tracking-wide">
                <div>Username</div>
                <div>Role</div>
            </div>
            <div
                v-for="user in userList"
                :key="user.id"
                class="grid grid-cols-3 gap-4 px-4 py-3 text-sm hover:bg-slate-50 cursor-pointer border-t items-center"
                role="button"
                tabindex="0"
                @click="goToUser(user.id)"
            >
                <div>
                    {{ user.username }}
                </div>
                <div>
                    {{ getRoleLabels(user.roles) }}
                </div>
            </div>
        </div>
    </div>
</template>


<script setup lang="ts">
import type {UserData} from "~/services/dto/user-data";
import {getAdminUsers} from "~/services/auth";
import {ROLE} from "~/utils/constants";

const userList = ref<UserData[]>([])
const router = useRouter()
const roleLabelByValue = new Map(ROLE.map((role) => [role.value, role.label]))

const goToUser = (id: number) => {
    router.push(`/admin/user/${id}`)
}

const getRoleLabels = (roles?: string[]) => {
    if (!roles || roles.length === 0) {
        return ' ---'
    }

    return roles
        .map((role) => roleLabelByValue.get(role) ?? role)
        .join(', ')
}

onMounted(async () => {
    userList.value = await getAdminUsers()
})
</script>
