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

        <DataTable
            :columns="columns"
            :items="items"
            :loading="isLoading"
            empty-message="Aucun tag trouvé."
            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>

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

<script setup lang="ts">
import type { TaskTag } from '~/modules/project-management/services/dto/task-tag'
import { useTaskTagService } from '~/modules/project-management/services/task-tags'

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

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

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

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

async function onSaved() {
    await loadItems()
}

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