<template>
    <div>
        <div class="flex justify-between h-[52px] mb-[80px]">
            <div class="flex flex-1 mr-16">
                <UiStepper
                    :labels="SHIPMENT_STEP_LABELS"
                    :current-step="storeShipment?.currentStep ?? 0"
                    @select="handleStepSelect"

                />
            </div>
            <button
                type="button"
                class="flex flex-col justify-center uppercase text-xl bg-black text-white h-[50px] w-[272px] text-center"
                @click="saveAndHold"
            >Mettre en attente
            </button>
        </div>
        <ShipmentForm v-if="!storeShipment || storeShipment.currentStep === 0"/>
        <button
            v-if="storeShipment?.currentStep === 1">
            TEST ETAPE 2
        </button>
    </div>
</template>
<script setup lang="ts">

import {SHIPMENT_STEP_LABELS} from "~/constants/steps";
import {storeToRefs} from "pinia";
import {useShipmentStore} from "~/stores/shipment";

const shipmentStore = useShipmentStore()
const {current: storeShipment} = storeToRefs(shipmentStore)

const route = useRoute()
const router = useRouter()

const resolveShipmentId = (param: unknown) => {
    const idStr = Array.isArray(param) ? param[0] : param
    if (!idStr) {
        return null
    }
    const id = Number(idStr)
    return Number.isFinite(id) ? id : null
}

watch (
    () => route.params.id,
    async (param) => {
        const id = resolveShipmentId(param)
        if (id === null) {
            shipmentStore.clearCurrent()
            return
        }
        await shipmentStore.loadShipment(id)
    },
    {immediate: true}
)

const saveAndHold = async () => {
    if (!shipmentStore.current) {
        await router.push('/')
        return
    }
    await shipmentStore.updateShipment(shipmentStore.current.id, {
        currentStep: shipmentStore.current.currentStep,
        licencePlate: shipmentStore.current.licencePlate,
        shipmentDate: shipmentStore.current.shipmentDate
    })
    await router.push('/')
}
const handleStepSelect = async (step: number) => {
    if (!shipmentStore.current) {
        return
    }

    if (step === shipmentStore.current.currentStep) {
        return
    }

    await shipmentStore.updateShipment(shipmentStore.current.id, {
        currentStep: step
    })
    await shipmentStore.loadShipment(shipmentStore.current.id)
}


</script>
