<template>
    <form @submit.prevent="validate">
        <div class="grid grid-cols-1 items-start gap-8 mb-16">
            <h1 class="font-bold text-5xl uppercase">Réception</h1>
            <div>
                <UiLicensePlateInput
                    v-model="form.licensePlate"
                    v-model:allowAny="allowAnyLicensePlate"
                />
            </div>
            <div class="flex flex-col">
                <label for="reception-date" class="font-bold uppercase text-xl mb-4">Date de reception</label>
                <input
                    id="reception-date"
                    v-model="form.receptionDate"
                    type="date"
                    class="border-b border-black justify-self-start text-xl pb-[6px] uppercase"
                />
            </div>
        </div>
        <div class="flex justify-center">
            <button
                type="submit"
                class="text-xl uppercase bg-primary-500 text-white h-[50px] w-[272px] justify-self-end"
            >Peser
            </button>
        </div>
    </form>
</template>

<script setup lang="ts">
import { useReceptionStore } from '~/stores/reception'

type ReceptionFormData = {
    licensePlate: string
    receptionDate: string
}

const router = useRouter()
const receptionStore = useReceptionStore()
const form = reactive<ReceptionFormData>({
    licensePlate: '',
    receptionDate: new Date().toISOString().slice(0, 10)
})
const allowAnyLicensePlate = ref(false)

watch(
    () => receptionStore.current,
    (reception) => {
        form.licensePlate = reception?.licensePlate ?? ''
        form.receptionDate = reception?.receptionDate ?? new Date().toISOString().slice(0, 10)
    },
    { immediate: true }
)

async function validate() {
    const normalizedLicensePlate = form.licensePlate.trim()
    const normalizedReceptionDate = form.receptionDate.trim()

    if (!receptionStore.current) {
        const created = await receptionStore.createReception({
            currentStep: 1,
            licensePlate: normalizedLicensePlate,
            receptionDate: normalizedReceptionDate
        })
        if (created) {
            await router.push(`/reception/${created.id}`)
        }
        return
    }

    const nextStep = receptionStore.current.currentStep + 1
    await receptionStore.updateReception(receptionStore.current.id, {
        currentStep: nextStep,
        licensePlate: normalizedLicensePlate,
        receptionDate: normalizedReceptionDate
    })
}

</script>
