<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 réceptions 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="goToReception"
            >
                <template #cell-receptionDate="{ item }">
                    {{ formatDate(item.receptionDate) }}
                </template>
                <template #cell-weighing="{ item }">
                    {{ formatWeighing(item) }}
                </template>
            </UiDataTable>
        </div>
    </div>
</template>

<script setup lang="ts">
import type { ReceptionData } from '~/services/dto/reception-data'
import { useDataTableServerState } from '~/composables/useDataTableServerState'

const router = useRouter()

const { items, totalItems, page, perPage, loading, reload } =
    useDataTableServerState<ReceptionData>(
        'receptions',
        { isValid: true },
        { initialPerPage: 5 }
    )

const columns = [
    { key: 'identificationNumber', label: 'Numéro' },
    { key: 'receptionDate', label: 'Date et heure' },
    { key: 'supplier.name', label: 'Fournisseur' },
    { key: 'address.fullAddress', label: 'Adresse' },
    { key: 'receptionType.label', label: 'Type réception' },
    { key: 'weighing', label: 'Poids' }
]

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

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

    return `${gross - tare} kg`
}

const goToReception = (reception: ReceptionData) => {
    router.push(`/reception/update/${reception.id}`)
}

onMounted(reload)
</script>
