<template>
    <div>
        <!-- En-tete -->
        <div class="flex items-center justify-between">
            <h1 class="text-xl font-bold text-primary-500 sm:text-2xl">
                {{ t('admin.users.title') }}
            </h1>
        </div>

        <!-- Table des utilisateurs -->
        <MalioDataTable
            class="mt-6"
            :columns="columns"
            :items="userItems"
            :total-items="users.length"
            :row-clickable="canManage"
            :empty-message="t('admin.users.noUsers')"
            @row-click="onRowClick"
        >
            <template #cell-admin="{ item }">
                <span
                    v-if="item.admin"
                    class="inline-flex items-center rounded-full bg-purple-100 px-2.5 py-0.5 text-xs font-medium text-purple-800"
                >
                    {{ t('admin.users.table.admin') }}
                </span>
            </template>
        </MalioDataTable>

        <!-- Drawer RBAC -->
        <UserRbacDrawer
            v-model="drawerOpen"
            :user="selectedUser"
            @saved="onUserSaved"
        />
    </div>
</template>

<script setup lang="ts">
import type { UserListItem } from '~/shared/types/rbac'

const { t } = useI18n()
const api = useApi()
const { can } = usePermissions()

useHead({ title: t('admin.users.title') })

const canManage = computed(() => can('core.users.manage'))

const users = ref<UserListItem[]>([])
const loading = ref(false)
const drawerOpen = ref(false)
const selectedUser = ref<UserListItem | null>(null)

// La colonne "Sites" n'est plus affichee dans la liste : le detail des sites
// rattaches est consulte/edite via le drawer (GET /users/{id}/rbac). Garder
// un payload leger sur /api/users facilite la pagination et evite de fuiter
// l'info cross-site aux users partageant juste un site avec l'appelant.
const columns = [
    { key: 'username', label: t('admin.users.table.username') },
    { key: 'admin', label: t('admin.users.table.admin') },
    { key: 'roles', label: t('admin.users.table.roles') },
    { key: 'directPermissions', label: t('admin.users.table.directPermissions') },
]

const userItems = computed(() =>
    users.value.map(user => ({
        id: user.id,
        username: user.username,
        admin: user.isAdmin,
        roles: user.roles.length,
        directPermissions: user.directPermissions.length,
    })),
)

async function loadUsers() {
    loading.value = true
    try {
        const usersData = await api.get<{ member: UserListItem[] }>('/users', {}, { toast: false })
        users.value = usersData.member
    } catch {
        // Reset sur echec pour ne pas afficher de donnees stale (ancienne
        // requete reussie avant une perte reseau ou 403). Pas de toast par
        // design ici : on laisse la liste vide parler d'elle-meme.
        users.value = []
    } finally {
        loading.value = false
    }
}

function getUserById(id: number): UserListItem | undefined {
    return users.value.find(u => u.id === id)
}

function openDrawer(user: UserListItem) {
    selectedUser.value = user
    drawerOpen.value = true
}

function onRowClick(item: Record<string, unknown>) {
    const user = getUserById(item.id as number)
    if (user) openDrawer(user)
}

function onUserSaved() {
    loadUsers()
}

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