<template>
    <div>
        <div class="flex items-center justify-between">
            <h2 class="text-lg font-bold text-neutral-900">{{ $t('workflows.title') }}</h2>
            <MalioButton
                icon-name="mdi:plus"
                icon-position="left"
                button-class="w-auto px-4"
                :label="$t('workflows.addWorkflow')"
                @click="openCreate"
            />
        </div>

        <DataTable
            :columns="columns"
            :items="items"
            :loading="isLoading"
            empty-message="Aucun workflow trouvé."
            deletable
            @row-click="openEdit"
            @delete="requestDelete"
        >
            <template #cell-isDefault="{ item }">
                <span
                    v-if="item.isDefault"
                    class="rounded bg-primary-100 px-2 py-0.5 text-xs font-medium text-primary-700"
                >
                    {{ $t('workflows.isDefault') }}
                </span>
            </template>
            <template #cell-statusCount="{ item }">
                {{ item.statuses.length }}
            </template>
        </DataTable>

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

<script setup lang="ts">
import type { Workflow } from '~/modules/project-management/services/dto/workflow'
import { useWorkflowService } from '~/modules/project-management/services/workflows'
import type { DataTableColumn } from '~/components/ui/DataTable.vue'

const { t } = useI18n()

const columns: DataTableColumn[] = [
    { key: 'name',        label: t('workflows.name'),     primary: true },
    { key: 'isDefault',   label: t('workflows.isDefault') },
    { key: 'statusCount', label: t('workflows.statuses') },
    { key: 'position',    label: 'Position' },
]

const workflowService = useWorkflowService()

const items = ref<Workflow[]>([])
const isLoading = ref(true)
const drawerOpen = ref(false)
const selectedItem = ref<Workflow | null>(null)

async function loadItems() {
    isLoading.value = true
    try {
        items.value = await workflowService.getAll()
    } finally {
        isLoading.value = false
    }
}

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

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

async function requestDelete(item: Workflow) {
    try {
        await workflowService.remove(item.id)
        await loadItems()
    } catch {
        // Toast d'erreur déjà émis par useApi
    }
}

async function onSaved() {
    await loadItems()
}

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