<template>
    <div>
        <div class="flex items-center justify-between">
            <h2 class="text-lg font-bold text-neutral-900">Groupes</h2>
            <button
                class="rounded-md bg-primary-500 px-4 py-2 text-sm font-semibold text-white hover:bg-secondary-500"
                @click="openCreate"
            >
                + Ajouter un groupe
            </button>
        </div>

        <DataTable
            :columns="columns"
            :items="items"
            :loading="isLoading"
            empty-message="Aucun groupe 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>
            <template #cell-description="{ item }">
                {{ item.description ?? '—' }}
            </template>
        </DataTable>

        <TaskGroupDrawer
            v-model="drawerOpen"
            :group="selectedItem"
            :project-id="projectId"
            @saved="onSaved"
        />
    </div>
</template>

<script setup lang="ts">
import type { TaskGroup } from '~/services/dto/task-group'
import { useTaskGroupService } from '~/services/task-groups'

const props = defineProps<{
    projectId: number
}>()

const emit = defineEmits<{
    (e: 'updated'): void
}>()

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

const columns: DataTableColumn[] = [
    { key: 'title', label: 'Titre', primary: true },
    { key: 'color', label: 'Couleur' },
    { key: 'description', label: 'Description', class: 'max-w-xs truncate text-neutral-700' },
]

const { getByProject, remove } = useTaskGroupService()
const items = ref<TaskGroup[]>([])
const isLoading = ref(true)
const drawerOpen = ref(false)
const selectedItem = ref<TaskGroup | null>(null)

async function loadItems() {
    isLoading.value = true
    try {
        items.value = await getByProject(props.projectId)
    } finally {
        isLoading.value = false
    }
}

function openCreate() {
    selectedItem.value = null
    drawerOpen.value = true
}

function openEdit(item: TaskGroup) {
    selectedItem.value = item
    drawerOpen.value = true
}

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

async function onSaved() {
    await loadItems()
    emit('updated')
}

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