<template>
    <WorkflowWaitingList
        title="listes des réceptions en attente"
        :columns="columns"
        :items="receptionList ?? []"
        route-prefix="/reception"
        :show-actions="auth.canUseWorkflow"
        :can-open-items="auth.canUseWorkflow"
    >
        <template #cell-receptionDate="{ item }">
            {{ formatDate(item.receptionDate) }}
        </template>
        <template #actions="{ item }">
            <Icon
                name="mdi:delete-outline"
                size="24"
                class="cursor-pointer text-red-500 hover:text-red-700"
                @click="confirmDelete(item)"
            />
        </template>
    </WorkflowWaitingList>
</template>

<script setup lang="ts">
import type { ReceptionData } from '~/services/dto/reception-data'
import { getReceptionList, deleteReception } from '~/services/reception'
import { useAuthStore } from '~/stores/auth'

const auth = useAuthStore()

const columns = [
    { key: 'receptionDate', label: 'Date et heure' },
    { key: 'supplier.name', label: 'Fournisseur' },
    { key: 'address.fullAddress', label: 'Adresse' },
    { key: 'receptionType.label', label: 'Type réception' },
    { key: 'carrier.name', label: 'Transporteur' },
    { key: 'licensePlate', label: 'Immatriculation' }
]

const receptionList = ref<ReceptionData[]>()

const formatDate = (date: string | null) => {
    if (!date) return '—'
    const d = new Date(date.replace(' ', 'T'))
    if (isNaN(d.getTime())) return date
    return d.toLocaleDateString('fr-FR', {
        day: '2-digit',
        month: '2-digit',
        year: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
    })
}

const confirmDelete = async (reception: ReceptionData) => {
    const confirmed = window.confirm(
        `Êtes-vous sûr de vouloir supprimer la réception ${reception.identificationNumber ?? `#${reception.id}`} ? Toutes les données liées seront supprimées.`
    )
    if (!confirmed) return

    await deleteReception(reception.id)
    receptionList.value = receptionList.value?.filter(r => r.id !== reception.id)
}

onMounted(async () => {
    receptionList.value = await getReceptionList(false)
})
</script>
