<template>
    <div>
        <PageHeader>{{ t('admin.users.title') }}</PageHeader>

        <!-- Table des utilisateurs — pagination serveur via usePaginatedList (#73). -->
        <MalioDataTable
            :columns="columns"
            :items="userItems"
            :total-items="totalItems"
            :page="currentPage"
            :per-page="itemsPerPage"
            :per-page-options="itemsPerPageOptions"
            :row-clickable="canManage"
            :empty-message="t('admin.users.noUsers')"
            @row-click="onRowClick"
            @update:page="goToPage"
            @update:per-page="setItemsPerPage"
        >
            <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 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 { can } = usePermissions()

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

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

// Pagination serveur via le composable partage (#73). Le payload `users`
// reste leger (pas de detail RBAC dans la liste — cf. commentaire colonne
// "Sites" plus bas) ce qui rend la pagination 10/25/50 par page confortable.
const {
    items: users,
    totalItems,
    currentPage,
    itemsPerPage,
    itemsPerPageOptions,
    fetch: loadUsers,
    goToPage,
    setItemsPerPage,
} = usePaginatedList<UserListItem>({ url: '/users' })

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,
    })),
)

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>
