<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">listes des expéditions finie</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"
                row-clickable
                @row-click="goToShipment"
            >
                <template #header-identificationNumber>
                    <UiTextInput
                        v-model="filters.identificationNumber"
                        placeholder="Numéro"
                        size="compact"
                    />
                </template>
                <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édition"
                        :options="shipmentTypeOptions"
                        size="compact"
                    />
                </template>
                <template #header-weighing>
                    <UiTextInput :model-value="''" placeholder="Poids" 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 #cell-weighing="{ item }">
                    {{ formatWeighing(item) }}
                </template>
            </UiDataTable>
        </div>
    </div>
</template>

<script setup lang="ts">
import type { ShipmentData } from '~/services/dto/shipment-data'
import type { ShipmentTypeData } from '~/services/dto/shipment-type-data'
import { getShipmentTypeList } from '~/services/shipment-type'
import { useDataTableServerState } from '~/composables/useDataTableServerState'

const router = useRouter()
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: true,
            'identificationNumber': '',
            'customer.name': '',
            '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: 'identificationNumber', label: 'Numéro', width: '75px' },
    { 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édition", width: '1.1fr' },
    { key: 'weighing', label: 'Poids', width: '82px' }
]

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 formatWeighing = (shipment: ShipmentData) => {
    const gross = shipment.weights?.find((weight) => weight.type === 'gross')?.weight
    const tare = shipment.weights?.find((weight) => weight.type === 'tare')?.weight

    if (gross == null || tare == null) {
        return '—'
    }

    return `${gross - tare} kg`
}

const goToShipment = (shipment: ShipmentData) => {
    router.push(`/shipment/update/${shipment.id}`)
}

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