<template>
    <div>
        <div class="flex justify-between h-[52px] mb-[80px]">
            <div class="flex flex-1 mr-16">
                <UiStepper
                    :labels="stepLabels"
                    :current-step="storeShipment?.currentStep ?? 0"
                    @select="handleStepSelect"
                />
            </div>
            <UiButton
                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
            </UiButton>
        </div>
        <ShipmentForm v-if="!storeShipment || storeShipment.currentStep === 0" ref="shipmentFormRef"/>
        <WorkflowWeight
            v-if="storeShipment?.currentStep === 1"
            ref="tareWeightRef"
            mode="tare"
            entity-name="shipment"
            api-resource="shipments"
            :title-label="shipmentConfig.weighingLabels.tare"
            :is-final="false"
            :entity="storeShipment"
            :get-weight-from-scale="getWeightShipment"
            :update-entity="shipmentStore.updateShipment"
            :load-entity="shipmentStore.loadShipment"
            :clear-entity="shipmentStore.clearCurrent"
            :build-receipt-filename="shipmentConfig.buildReceiptFilename"
        />
        <ShipmentLoading v-if="storeShipment?.currentStep === 2"/>
        <WorkflowWeight
            v-if="storeShipment?.currentStep === 3"
            ref="grossWeightRef"
            mode="gross"
            entity-name="shipment"
            api-resource="shipments"
            :title-label="shipmentConfig.weighingLabels.gross"
            :is-final="true"
            :entity="storeShipment"
            :get-weight-from-scale="getWeightShipment"
            :update-entity="shipmentStore.updateShipment"
            :load-entity="shipmentStore.loadShipment"
            :clear-entity="shipmentStore.clearCurrent"
            :build-receipt-filename="shipmentConfig.buildReceiptFilename"
        />
    </div>
</template>

<script setup lang="ts">
useHead({ title: 'Expédition' })

import { storeToRefs } from 'pinia'
import { useShipmentStore } from '~/stores/shipment'
import { useWorkflowSteps } from '~/composables/useWorkflowSteps'
import { shipmentConfig } from '~/config/shipment.config'
import { getWeightShipment } from '~/services/shipment'
import { ref, watch } from 'vue'

const shipmentStore = useShipmentStore()
const { current: storeShipment } = storeToRefs(shipmentStore)
const shipmentFormRef = ref<{ saveDraft: () => Promise<void>, validateFields: () => boolean } | null>(null)
const grossWeightRef = ref<{ saveWeightDraft: () => Promise<void> } | null>(null)
const tareWeightRef = ref<{ saveWeightDraft: () => Promise<void> } | null>(null)

const { stepLabels, handleStepSelect } = useWorkflowSteps(shipmentConfig, shipmentStore)

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

watch(
    () => route.params.id,
    async (param) => {
        const idStr = Array.isArray(param) ? param[0] : param
        if (!idStr) {
            shipmentStore.clearCurrent()
            return
        }
        const id = Number(idStr)
        if (Number.isFinite(id)) {
            await shipmentStore.loadShipment(id)
        }
    },
    { immediate: true }
)

const saveAndHold = async () => {
    if (shipmentFormRef.value) {
        if (!shipmentFormRef.value.validateFields()) return
        await shipmentFormRef.value.saveDraft()
    } else {
        if (grossWeightRef.value) await grossWeightRef.value.saveWeightDraft()
        if (tareWeightRef.value) await tareWeightRef.value.saveWeightDraft()
    }
    await router.push('/')
}
</script>
