<template>
    <div class="flex justify-between h-[52px] mb-[80px]">
        <div class="flex flex-1 mr-16">
            <UiStepper
                :labels="stepLabels"
                :current-step="storeReception?.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>
    <ReceptionForm v-if="!storeReception || storeReception.currentStep === 0" ref="receptionFormRef"/>
    <WorkflowWeight
        v-if="storeReception?.currentStep === 1"
        ref="grossWeightRef"
        mode="gross"
        entity-name="reception"
        api-resource="receptions"
        :title-label="receptionConfig.weighingLabels.gross"
        :is-final="false"
        :entity="storeReception"
        :get-weight-from-scale="getWeight"
        :update-entity="receptionStore.updateReception"
        :load-entity="receptionStore.loadReception"
        :clear-entity="receptionStore.clearCurrent"
        :build-receipt-filename="receptionConfig.buildReceiptFilename"
    />
    <ReceptionProductReceived
        v-if="storeReception?.currentStep === 2 &&
            receptionStore.current?.receptionType?.code === RECEPTION_TYPE_CODES.MERCHANDISES"/>
    <ReceptionBovineReceived
        v-if="storeReception?.currentStep === 2 &&
            receptionStore.current?.receptionType?.code === RECEPTION_TYPE_CODES.BOVINS"/>
    <WorkflowWeight
        v-if="storeReception?.currentStep !== null && storeReception?.currentStep >= 3"
        ref="tareWeightRef"
        mode="tare"
        entity-name="reception"
        api-resource="receptions"
        :title-label="receptionConfig.weighingLabels.tare"
        :is-final="true"
        :entity="storeReception"
        :get-weight-from-scale="getWeight"
        :update-entity="receptionStore.updateReception"
        :load-entity="receptionStore.loadReception"
        :clear-entity="receptionStore.clearCurrent"
        :build-receipt-filename="receptionConfig.buildReceiptFilename"
    />
</template>

<script setup lang="ts">
import { useReceptionStore } from '~/stores/reception'
import { storeToRefs } from 'pinia'
import { useWorkflowSteps } from '~/composables/useWorkflowSteps'
import { receptionConfig } from '~/config/reception.config'
import { getWeight } from '~/services/reception'
import { RECEPTION_TYPE_CODES } from '~/utils/constants'

const receptionStore = useReceptionStore()
const { current: storeReception } = storeToRefs(receptionStore)
const receptionFormRef = 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(receptionConfig, receptionStore)

const router = useRouter()

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

// Init route watcher
const route = useRoute()
watch(
    () => route.params.id,
    async (param) => {
        const idStr = Array.isArray(param) ? param[0] : param
        if (!idStr) {
            receptionStore.clearCurrent()
            return
        }
        const id = Number(idStr)
        if (Number.isFinite(id)) {
            await receptionStore.loadReception(id)
        }
    },
    { immediate: true }
)
</script>
