
<template>
    <form @submit.prevent="validate">
    <div class="flex items-center justify-between">
        <h1 class="text-3xl font-bold uppercase">
            {{ route.params.id ? 'Modifier transporteur' : 'Ajout transporteur' }}
        </h1>

        <UiButton
            type="submit"
            class="inline-flex items-center justify-center text-xl text-white uppercase bg-primary-500 h-[50px] px-8 rounded hover:opacity-80 gap-2 justify-self-end"
        >
            <Icon name="mdi:check" size="28" />
            Valider
        </UiButton>
    </div>

    <div class="grid grid-cols-2 items-start gap-y-8 gap-x-40 py-12">
        <UiTextInput
            label = "nom du fournisseur"
            id="carrier-name"
            v-model="form.name"
        />

        <UiTextInput
                label = "code fournisseur"
                id="code-id"
                v-model="form.code"
        />
    </div>
    </form>

</template>

<script setup lang="ts">
import {createCarrier, getCarrier, updateCarrier} from "~/services/carrier";
import type {CarrierData, CarrierFormData} from "~/services/dto/carrier-data";
import {computed} from "vue";
const router = useRouter()
const route = useRoute()
const idCarrier = computed(() => resolveId(route.params.id))
const isLoading = ref(false)
const isHydrating = ref(false)

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

const form = reactive<CarrierFormData>({
    code:'',
    name:''
})

const hydrateFromUser = (carrier: CarrierData | null) => {
    if (!carrier) {
        return
    }
    isHydrating.value = true
    form.name = carrier.name ?? ''
    form.code = carrier.code ?? ''
    isHydrating.value = false
}

watch(
    () => idCarrier.value,
    async (id) => {
        if (id === null) {
            return
        }
        isLoading.value = true
        try {
            const user = await getCarrier(id)
            hydrateFromUser(user)
        } finally {
            isLoading.value = false
        }
    },
    {immediate: true}
)
async function validate() {

    const normalizedCarrierCode = form.code.trim()
    const normalizedCarrierName = form.name.trim()

    const basePayload = {
        name: normalizedCarrierName,
        code: normalizedCarrierCode

    }

    if(idCarrier.value){
        await updateCarrier(idCarrier.value, basePayload)
        navigate()
        return
    }
    await createCarrier(basePayload)
    navigate()
}

function navigate(){
    router.push("/admin/carrier/carrier-list")
}
</script>
