<template>
    <div>
        <h1 class="text-3xl font-bold">Liste des receptions</h1>
        <div class="mt-6 border border-slate-200">
            <div class="grid grid-cols-6 gap-4 bg-slate-100 px-4 py-3 text-sm font-semibold uppercase tracking-wide">
                <div>ID</div>
                <div>Immatriculation</div>
                <div>Pesée plein</div>
                <div>Pesée vide</div>
                <div>Etape</div>
                <div>Date</div>
            </div>
            <div
                v-for="reception in receptionList"
                :key="reception.id"
                class="grid grid-cols-6 gap-4 px-4 py-3 text-sm hover:bg-slate-50 cursor-pointer border-t border-slate-200"
                role="button"
                tabindex="0"
                @click="goToReception(reception.id)"
                @keydown.enter="goToReception(reception.id)"
            >
                <div>{{ reception.id }}</div>
                <div>{{ reception.licensePlate }}</div>
                <div>{{ formatWeighing(reception, 'gross') }}</div>
                <div>{{ formatWeighing(reception, 'tare') }}</div>
                <div>{{ reception.currentStep }}</div>
                <div>{{ reception.receptionDate }}</div>
            </div>
        </div>
    </div>
</template>

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

const receptionList = ref<ReceptionData[]>()
const router = useRouter()

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

const formatWeighing = (reception: ReceptionData, type: 'gross' | 'tare') => {
    const entry = reception.weights?.find((weight) => weight.type === type)
    if (!entry || entry.weight == null || entry.dsd == null) {
        return '—'
    }
    return `${entry.weight} kg / ${entry.dsd} dsd`
}

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