<template>
    <WorkflowWaitingList
        title="listes des expéditions en attente"
        :columns="columns"
        :items="shipmentList ?? []"
        route-prefix="/shipment"
        show-actions
    >
        <template #cell-shipmentDate="{ item }">
            {{ formatDate(item.shipmentDate) }}
        </template>
        <template #cell-shipmentType="{ item }">
            <template v-if="formatShipmentLines(item).length">
                <div
                    v-for="(line, index) in formatShipmentLines(item)"
                    :key="index"
                    class="leading-5"
                >
                    {{ line }}
                </div>
            </template>
            <template v-else>—</template>
        </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 { ShipmentData } from '~/services/dto/shipment-data'
import { getShipmentList, deleteShipment } from '~/services/shipment'

const columns = [
    { key: 'shipmentDate', label: 'Date et heure' },
    { key: 'customer.name', label: 'Client' },
    { key: 'address.fullAddress', label: 'Adresse' },
    { key: 'shipmentType', label: "Type d'expé." },
    { key: 'carrier.name', label: 'Transporteur' },
    { key: 'licensePlate', label: 'Immatriculation' }
]

const shipmentList = ref<ShipmentData[]>()

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 formatShipmentLines = (shipment: ShipmentData) => {
    if (!shipment.shipmentType && shipment.nbBovinSend == null) {
        return []
    }
    const label = typeof shipment.shipmentType === 'string'
        ? shipment.shipmentType
        : shipment.shipmentType?.label
    return [`${label ?? '—'} : ${shipment.nbBovinSend ?? '—'}`]
}

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

    await deleteShipment(shipment.id)
    shipmentList.value = shipmentList.value?.filter(s => s.id !== shipment.id)
}

onMounted(async () => {
    shipmentList.value = await getShipmentList(false)
})
</script>
