<template>
    <div class="flex items-center justify-start gap-10">
        <Icon @click="router.push('/')" name="gg:arrow-left-o" size="44" class="cursor-pointer text-primary-500"/>
        <h1 class="text-3xl font-bold uppercase text-primary-500">liste des expéditions en attente</h1>
    </div>

    <div class="px-[86px]">
        <div class="mt-6 mb-16">
            <UiDataTable
                v-model:page="page"
                v-model:per-page="perPage"
                :columns="columns"
                :items="items"
                :total-items="totalItems"
                :loading="loading"
                :show-actions="auth.isAdmin"
                row-clickable
                @row-click="goToShipment"
            >
                <template #header-shipmentDate>
                    <UiDateMaskedInput v-model="shipmentDateFilter" placeholder="Date" size="compact" />
                </template>
                <template #header-customer.name>
                    <UiTextInput
                        v-model="filters['customer.name']"
                        placeholder="Client"
                        size="compact"
                    />
                </template>
                <template #header-address.fullAddress>
                    <UiTextInput :model-value="''" placeholder="Adresse" size="compact" disabled />
                </template>
                <template #header-shipmentType.label>
                    <UiSelect
                        v-model="filters['shipmentType.id']"
                        placeholder="Type d'expé."
                        :options="shipmentTypeOptions"
                        size="compact"
                    />
                </template>
                <template #header-carrier.name>
                    <UiTextInput
                        v-model="filters['carrier.name']"
                        placeholder="Transporteur"
                        size="compact"
                    />
                </template>
                <template #header-licensePlate>
                    <UiTextInput
                        v-model="filters['licensePlate']"
                        placeholder="Immatriculation"
                        size="compact"
                    />
                </template>
                <template #header-actions>
                    <UiTextInput :model-value="''" placeholder="Actions" size="compact" disabled />
                </template>
                <template #cell-shipmentDate="{ item }">
                    {{ formatDate(item.shipmentDate) }}
                </template>
                <template #cell-shipmentType.label="{ 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>
            </UiDataTable>
        </div>
    </div>
</template>

<script setup lang="ts">
useHead({ title: 'Expéditions en attente' })

import type { ShipmentData } from '~/services/dto/shipment-data'
import type { ShipmentTypeData } from '~/services/dto/shipment-type-data'
import { deleteShipment } from '~/services/shipment'
import { getShipmentTypeList } from '~/services/shipment-type'
import { useAuthStore } from '~/stores/auth'
import { useDataTableServerState } from '~/composables/useDataTableServerState'

const router = useRouter()
const auth = useAuthStore()
const shipmentTypes = ref<ShipmentTypeData[]>([])

const shipmentTypeOptions = computed(() =>
    shipmentTypes.value.map(st => ({ value: st.id, label: st.label }))
)

const { items, totalItems, page, perPage, filters, loading, reload } =
    useDataTableServerState<ShipmentData>(
        'shipments',
        {
            isValid: false,
            'customer.name': '',
            'carrier.name': '',
            'licensePlate': '',
            'shipmentType.id': '',
            'shipmentDate[after]': '',
            'shipmentDate[strictly_before]': ''
        },
        { initialPerPage: 10 }
    )

const addOneDay = (dateString: string): string => {
    const [year, month, day] = dateString.split('-').map(Number)
    const next = new Date(Date.UTC(year, month - 1, day + 1))
    return next.toISOString().slice(0, 10)
}

const shipmentDateFilter = computed<string>({
    get: () => (filters.value['shipmentDate[after]'] as string) ?? '',
    set: (value: string) => {
        if (!value) {
            filters.value['shipmentDate[after]'] = ''
            filters.value['shipmentDate[strictly_before]'] = ''
            return
        }
        filters.value['shipmentDate[after]'] = value
        filters.value['shipmentDate[strictly_before]'] = addOneDay(value)
    }
})

const columns = [
    { key: 'shipmentDate', label: 'Date', width: '120px' },
    { key: 'customer.name', label: 'Client', width: '1.5fr' },
    { key: 'address.fullAddress', label: 'Adresse', width: '2fr' },
    { key: 'shipmentType.label', label: "Type d'expé.", width: '1.1fr' },
    { key: 'carrier.name', label: 'Transporteur' },
    { key: 'licensePlate', label: 'Immatriculation', width: '110px' }
]

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 goToShipment = (shipment: ShipmentData) => {
    router.push(`/shipment/${shipment.id}`)
}

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)
    reload()
}

onMounted(async () => {
    shipmentTypes.value = await getShipmentTypeList()
    reload()
})
</script>
