<template>
    <form @submit.prevent="validate">
        <div class="grid grid-cols-2 gap-x-40 gap-y-8 mb-8">
            <UiNumberInput
                label="Dsd"
                class="col-start-2"
                labelClass="font-bold uppercase"
                v-model="sharedWeightMeta.dsd"
                :disabled="!auth.isAdmin"
            />
            <UiDateInput
                label="Date pesée"
                v-model="sharedWeightMeta.weighedAt"
                :disabled="!auth.isAdmin"
            />
        </div>
        <div class="grid grid-cols-2 gap-x-40 mb-16">
            <UiNumberInput
                v-for="weight in form.weights"
                :key="weight.type"
                :label="getWeightLabel(weight.type)"
                labelClass="font-bold uppercase text-xl"
                inputClass="w-24"
                v-model="weight.weight"
                :wrapper-class="weight.type === 'tare' ? 'col-start-1 row-start-1' : 'col-start-2 row-start-1'"
                :disabled="!auth.isAdmin"
                :min="0"
                :max="48000"
            />
        </div>

        <div class="flex justify-center">
            <button
                v-if="auth.isAdmin"
                type="submit"
                class="text-xl uppercase bg-primary-500 text-white h-[50px] w-[272px]"

            >
                Valider
            </button>
        </div>

    </form>
</template>

<script setup lang="ts">
import type {ReceptionFormWeight} from '~/services/dto/reception-data'
import {getReception} from '~/services/reception'
import {updateWeight} from "~/services/weight";
import {useAuthStore} from "~/stores/auth";

const props = defineProps<{
    idReception: number
}>()

const idReception = props.idReception
const auth = useAuthStore()

const form = reactive({
    weights: [
        {id: 0, type: 'tare' as const, weight: 0, dsd: null, weighedAt: null},
        {id: 0, type: 'gross' as const, weight: 0, dsd: null, weighedAt: null}
    ]
})
// DSD et date de pesée sont partagés entre tare et gross dans l'UI.
const sharedWeightMeta = reactive<{
    dsd: number | string | null
    weighedAt: string | null
}>({
    dsd: null,
    weighedAt: null
})

const getWeightLabel = (type: 'tare' | 'gross'): string => {
    return type === 'tare' ? 'Pesée à vide' : 'Pesée à plein'
}

const hydrateFromReception = (reception: ReceptionFormWeight) => {
    // On hydrate chaque ligne par son type (tare/gross), sans dépendre d'un index.
    for (const receptionWeight of reception.weights) {
        const formWeight = form.weights.find(weight => weight.type === receptionWeight.type)
        if (formWeight) {
            Object.assign(formWeight, receptionWeight)
        }
    }

    // On récupère une valeur existante pour préremplir les champs partagés.
    const weightWithMeta = reception.weights.find(weight =>
        (weight.dsd !== null && weight.dsd !== undefined)
        || (weight.weighedAt !== null && weight.weighedAt !== undefined && weight.weighedAt !== '')
    )

    if (weightWithMeta) {
        sharedWeightMeta.dsd = weightWithMeta.dsd ?? null
        sharedWeightMeta.weighedAt = weightWithMeta.weighedAt ?? null
    }
}

onMounted(async () => {
    const reception = await getReception(idReception)
    hydrateFromReception(reception)
})

async function validate() {
    const sharedDsd =
        sharedWeightMeta.dsd === null || sharedWeightMeta.dsd === undefined || sharedWeightMeta.dsd === ''
            ? null
            : Number(sharedWeightMeta.dsd)
    const sharedWeighedAt =
        sharedWeightMeta.weighedAt === null || sharedWeightMeta.weighedAt === undefined || sharedWeightMeta.weighedAt === ''
            ? null
            : sharedWeightMeta.weighedAt
    for (const weight of form.weights) {
        if (weight.id) {
            await updateWeight(weight.id, {
                weight: weight.weight,
                dsd: Number.isFinite(sharedDsd) ? sharedDsd : null,
                weighedAt: sharedWeighedAt
            })
        }
    }

}
</script>
