<template>
    <div>
        <div class="flex items-center justify-between">
            <h2 class="text-lg font-bold text-neutral-900">Utilisateurs</h2>
            <MalioButton
                icon-name="mdi:plus"
                icon-position="left"
                button-class="w-auto px-4"
                label="Ajouter un utilisateur"
                @click="openCreate"
            />
        </div>

        <DataTable
            :columns="columns"
            :items="items"
            :loading="isLoading"
            empty-message="Aucun utilisateur trouvé."
            deletable
            @row-click="openEdit"
            @delete="(item) => handleDelete(item.id)"
        >
            <template #cell-roles="{ item }">
                <span
                    v-for="role in item.roles"
                    :key="role"
                    class="mr-1 rounded-full bg-neutral-200 px-2 py-0.5 text-xs font-semibold text-neutral-700"
                >
                    {{ role }}
                </span>
            </template>
        </DataTable>

        <UserDrawer
            v-model="drawerOpen"
            :item="selectedItem"
            @saved="onSaved"
        />
    </div>
</template>

<script setup lang="ts">
import type { UserData } from '~/services/dto/user-data'
import { useUserService } from '~/services/users'

import type { DataTableColumn } from '~/components/ui/DataTable.vue'

const columns: DataTableColumn[] = [
    { key: 'username', label: "Nom d'utilisateur", primary: true },
    { key: 'roles', label: 'Rôles' },
]

const { getAll, remove } = useUserService()
const items = ref<UserData[]>([])
const isLoading = ref(true)
const drawerOpen = ref(false)
const selectedItem = ref<UserData | null>(null)

async function loadItems() {
    isLoading.value = true
    try {
        items.value = await getAll()
    } finally {
        isLoading.value = false
    }
}

function openCreate() {
    selectedItem.value = null
    drawerOpen.value = true
}

function openEdit(item: UserData) {
    selectedItem.value = item
    drawerOpen.value = true
}

async function handleDelete(id: number) {
    await remove(id)
    await loadItems()
}

async function onSaved() {
    await loadItems()
}

onMounted(() => {
    loadItems()
})
</script>
