<template>
    <div>
        <PageHeader>
            {{ t('admin.roles.title') }}
            <template #actions>
                <MalioButton
                    v-if="can('core.roles.manage')"
                    variant="secondary"
                    :label="t('admin.roles.newRole')"
                    icon-name="mdi:add-bold"
                    icon-position="left"
                    @click="openCreateDrawer"
                />
            </template>
        </PageHeader>

        <!-- Table des roles — pagination serveur via usePaginatedList (#73). -->
        <MalioDataTable
            :columns="columns"
            :items="roleItems"
            :total-items="totalItems"
            :page="currentPage"
            :per-page="itemsPerPage"
            :per-page-options="itemsPerPageOptions"
            :row-clickable="canManage"
            :empty-message="t('admin.roles.noRoles')"
            @row-click="onRowClick"
            @update:page="goToPage"
            @update:per-page="setItemsPerPage"
        >
            <template #cell-code="{ item }">
                <span>{{ item.code }}</span>
            </template>
            <template #cell-permissions="{ item }">
                {{ item.permissions }}
            </template>
            <template #cell-system="{ item }">
                <span
                    v-if="item.isSystem"
                    class="inline-flex items-center rounded-full bg-blue-100 px-2.5 py-0.5 font-medium text-blue-800"
                >
                    {{ t('admin.roles.table.system') }}
                </span>
            </template>
        </MalioDataTable>

        <!-- Drawer creation/edition -->
        <RoleDrawer
            v-model="drawerOpen"
            :role="selectedRole"
            @saved="onRoleSaved"
            @delete="onDeleteRequest"
        />

        <!-- Modale de suppression -->
        <RoleDeleteModal
            v-model="deleteModalOpen"
            :role-label="roleToDelete?.label ?? ''"
            :loading="deleting"
            @confirm="handleDelete"
        />
    </div>
</template>

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

const { t } = useI18n()
const api = useApi()
const { can } = usePermissions()
const canManage = computed(() => can('core.roles.manage'))

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

// Pagination serveur via le composable partage (#73).
const {
    items: roles,
    totalItems,
    currentPage,
    itemsPerPage,
    itemsPerPageOptions,
    fetch: loadRoles,
    goToPage,
    setItemsPerPage,
} = usePaginatedList<Role>({ url: '/roles' })

const columns = [
    { key: 'label', label: t('admin.roles.table.label') },
    { key: 'code', label: t('admin.roles.table.code') },
    { key: 'permissions', label: t('admin.roles.table.permissions') },
    { key: 'system', label: t('admin.roles.table.system') },
]

// Transformer les roles en items compatibles MalioDataTable
const roleItems = computed(() =>
    roles.value.map(role => ({
        id: role.id,
        label: role.label,
        code: role.code,
        permissions: role.permissions.length,
        isSystem: role.isSystem,
        system: '', // colonne geree par le slot
    }))
)

function getRoleById(id: number): Role | undefined {
    return roles.value.find(r => r.id === id)
}

function onRowClick(item: Record<string, unknown>) {
    const role = getRoleById(item.id as number)
    if (role) openEditDrawer(role)
}
const drawerOpen = ref(false)
const selectedRole = ref<Role | null>(null)
const deleteModalOpen = ref(false)
const roleToDelete = ref<Role | null>(null)
const deleting = ref(false)

function openCreateDrawer() {
    selectedRole.value = null
    drawerOpen.value = true
}

function openEditDrawer(role: Role) {
    selectedRole.value = role
    drawerOpen.value = true
}

function onDeleteRequest() {
    if (!selectedRole.value || selectedRole.value.isSystem) return
    roleToDelete.value = selectedRole.value
    deleteModalOpen.value = true
}

async function handleDelete() {
    if (!roleToDelete.value) return
    deleting.value = true
    try {
        await api.delete(`/roles/${roleToDelete.value.id}`, {}, {
            toastSuccessMessage: t('admin.roles.toast.deleted'),
        })
        deleteModalOpen.value = false
        roleToDelete.value = null
        drawerOpen.value = false
        await loadRoles()
    } finally {
        deleting.value = false
    }
}

function onRoleSaved() {
    loadRoles()
}

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