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

        <DataTable
            :columns="columns"
            :items="items"
            :loading="isLoading"
            empty-message="Aucune priorité trouvée."
            deletable
            @row-click="openEdit"
            @delete="(item) => handleDelete(item.id)"
        >
            <template #cell-color="{ item }">
                <span
                    class="inline-block h-6 w-6 rounded-full"
                    :style="{ backgroundColor: item.color }"
                />
            </template>
        </DataTable>

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

<script setup lang="ts">
import type { TaskPriority } from '~/modules/project-management/services/dto/task-priority'
import { useTaskPriorityService } from '~/modules/project-management/services/task-priorities'

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

const columns: DataTableColumn[] = [
    { key: 'label', label: 'Libellé', primary: true },
    { key: 'color', label: 'Couleur' },
]

const { getAll, remove } = useTaskPriorityService()
const items = ref<TaskPriority[]>([])
const isLoading = ref(true)
const drawerOpen = ref(false)
const selectedItem = ref<TaskPriority | 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: TaskPriority) {
    selectedItem.value = item
    drawerOpen.value = true
}

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

async function onSaved() {
    await loadItems()
}

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