<template>
    <MalioDrawer
        :model-value="modelValue"
        drawer-class="w-full max-w-lg"
        header-class="border-b border-black"
        footer-class="justify-between border-t border-black p-6"
        @update:model-value="emit('update:modelValue', $event)"
    >
        <template #header>
            <h2 class="text-[24px] font-bold">
                {{ isEditMode ? t('admin.roles.editRole') : t('admin.roles.createRole') }}
            </h2>
        </template>
        <form class="flex flex-col py-4 gap-2" @submit.prevent="handleSave">
            <!-- Champs du role -->
            <MalioInputText
                v-model="form.label"
                :label="t('admin.roles.form.label')"
                input-class="w-full"
                required
            />

            <MalioInputText
                v-model="form.code"
                :label="t('admin.roles.form.code')"
                input-class="w-full"
                required
                :readonly="isEditMode"
            />

            <MalioInputTextArea
                v-model="form.description"
                :label="t('admin.roles.form.description')"
                input-class="w-full"
            />

            <!-- Permissions groupees par module -->
            <div>
                <h4 class="mb-3 text-sm font-semibold text-neutral-700">
                    {{ t('admin.roles.form.permissions') }}
                </h4>
                <!-- Etat d'erreur explicite : sans ce message, un drawer vide
                     ressemblerait a un role legitimement sans permissions. -->
                <div
                    v-if="permissionsLoadFailed"
                    class="rounded border border-red-200 bg-red-50 p-3 text-sm text-red-700"
                >
                    {{ t('admin.roles.permissions.loadFailed') }}
                </div>
                <div v-else-if="permissionsByModule.length === 0" class="text-sm text-neutral-400">
                    {{ t('admin.roles.permissions.noPermissions') }}
                </div>
                <PermissionAccordion
                    v-else
                    :groups-by-module="permissionsByModule"
                    :selected-ids="selectedPermissionIds"
                    id-prefix="role"
                    @toggle="handleTogglePermission"
                    @toggle-all="handleToggleAll"
                />
            </div>

        </form>

        <!-- Footer fixe : depuis la 1.7.1 le slot #footer est un frere du body
             scrollable (shrink-0), donc reellement fige sans sticky. -->
        <template #footer>
            <MalioButton
                v-if="isEditMode"
                :label="t('common.delete')"
                variant="danger"
                icon-name="mdi:delete-outline"
                icon-position="left"
                button-class="w-m-btn-action"
                :disabled="role?.isSystem"
                @click="emit('delete')"
            />
            <MalioButton
                v-else
                :label="t('common.cancel')"
                variant="tertiary"
                button-class="w-m-btn-action"
                @click="emit('update:modelValue', false)"
            />
            <MalioButton
                :label="isEditMode ? t('common.save') : t('common.validate')"
                variant="primary"
                button-class="w-m-btn-action"
                :disabled="saving || permissionsLoadFailed"
                @click="handleSave"
            />
        </template>
    </MalioDrawer>
</template>

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

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

const props = defineProps<{
    modelValue: boolean
    role: Role | null
}>()

const emit = defineEmits<{
    'update:modelValue': [value: boolean]
    saved: []
    delete: []
}>()

const saving = ref(false)
const allPermissions = ref<Permission[]>([])
// Signale un echec de chargement du catalogue de permissions : on bloque
// alors la sauvegarde pour eviter qu'un drawer ouvert avec zero permission
// visible (cas d'un 403 ou d'une panne reseau) n'ecrase silencieusement
// toutes les permissions du role.
const permissionsLoadFailed = ref(false)

const form = ref({
    label: '',
    code: '',
    description: '',
})

const selectedPermissionIds = ref(new Set<number>())

const isEditMode = computed(() => props.role !== null)

// Grouper les permissions par module
const permissionsByModule = computed<PermissionModule[]>(() => {
    const groups = new Map<string, Permission[]>()
    for (const perm of allPermissions.value) {
        if (perm.orphan) continue
        const list = groups.get(perm.module) || []
        list.push(perm)
        groups.set(perm.module, list)
    }
    return Array.from(groups.entries())
        .map(([module, permissions]) => ({ module, permissions }))
        .sort((a, b) => a.module.localeCompare(b.module))
})

// Charger les permissions au montage
async function loadPermissions() {
    permissionsLoadFailed.value = false
    try {
        const data = await api.get<{ member: Permission[] }>(
            '/permissions',
            { 'orphan': false, itemsPerPage: 999 },
            // `toast: true` : en cas d'echec (403, reseau, 500), l'utilisateur
            // voit l'erreur remonter. Sans ce feedback, un catalogue vide
            // ressemblerait a un role sans permissions disponibles.
            { toast: true },
        )
        allPermissions.value = data.member
    } catch {
        allPermissions.value = []
        permissionsLoadFailed.value = true
    }
}

// Remplir le formulaire quand le role change
watch(() => props.role, (role) => {
    if (role) {
        form.value.label = role.label
        form.value.code = role.code
        form.value.description = role.description || ''
        selectedPermissionIds.value = new Set(role.permissions.map(p => {
            // L'API peut retourner des objets Permission ou des IRIs string
            if (typeof p === 'string') {
                return Number(p.split('/').pop())
            }
            return p.id
        }))
    } else {
        form.value.label = ''
        form.value.code = ''
        form.value.description = ''
        selectedPermissionIds.value = new Set()
    }
}, { immediate: true })

// Charger les permissions quand le drawer s'ouvre
watch(() => props.modelValue, (open) => {
    if (open) loadPermissions()
})

// Basculer une permission individuelle
function handleTogglePermission(id: number, selected: boolean) {
    const ids = new Set(selectedPermissionIds.value)
    if (selected) {
        ids.add(id)
    } else {
        ids.delete(id)
    }
    selectedPermissionIds.value = ids
}

// Basculer toutes les permissions d'un module
function handleToggleAll(module: string, selected: boolean) {
    const ids = new Set(selectedPermissionIds.value)
    const group = permissionsByModule.value.find(g => g.module === module)
    if (!group) return
    for (const perm of group.permissions) {
        if (selected) {
            ids.add(perm.id)
        } else {
            ids.delete(perm.id)
        }
    }
    selectedPermissionIds.value = ids
}

// Sauvegarder le role (creation ou edition)
async function handleSave() {
    saving.value = true
    try {
        const permissions = Array.from(selectedPermissionIds.value).map(id => `/api/permissions/${id}`)

        if (isEditMode.value && props.role) {
            // Le code est immuable apres creation (garde backend RoleProcessor)
            await api.patch(`/roles/${props.role.id}`, {
                label: form.value.label,
                description: form.value.description || null,
                permissions,
            }, {
                toastSuccessMessage: t('admin.roles.toast.updated'),
            })
        } else {
            await api.post('/roles', {
                label: form.value.label,
                code: form.value.code,
                description: form.value.description || null,
                permissions,
            }, {
                toastSuccessMessage: t('admin.roles.toast.created'),
            })
        }

        emit('saved')
        emit('update:modelValue', false)
    } finally {
        saving.value = false
    }
}
</script>
