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

            <UiButton
                type="submit"
                :disabled="isLoading || isHydrating"
                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"
            >
                <Icon :name="isEdit ? '' : 'mdi:plus'" size="28" />
                {{ isEdit ? 'Valider' : 'Ajouter' }}
            </UiButton>
        </div>

        <div class="grid grid-cols-2 items-start gap-y-8 gap-x-40 py-12">
            <UiTextInput label="Nom du bovin" id="bovin-label" v-model="form.label" />
            <UiTextInput label="Code bovin" id="code-id" v-model="form.code" />
        </div>
    </form>
</template>

<script setup lang="ts">
import {createBovin, getBovin, updateBovin} from "~/services/bovine-type";
import type {BovineTypeData, BovinFormData} from "~/services/dto/bovine-type-data";
const router = useRouter()
const route = useRoute()
const isLoading = ref(false)
const isHydrating = ref(false)

function 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 idBovin = computed(() => resolveId(route.params.id))
const isEdit = computed(() => idBovin.value !== null)

const form = reactive<BovinFormData>({
    label: '',
    code: ''
})


const hydrateFromBovin = (bovin: BovineTypeData | null) => {
    if (!bovin) {
        return
    }
    isHydrating.value = true
    form.label = bovin.label ?? ''
    form.code = bovin.code ?? ''
    isHydrating.value = false
}

watch(
    () => idBovin.value,
    async (id) => {
        if (id === null) {
            return
        }
        isLoading.value = true
        try {
            const bovin = await getBovin(id)
            hydrateFromBovin(bovin)
        } finally {
            isLoading.value = false
        }
    },
    {immediate: true}
)
async function validate() {
    if (isLoading.value || isHydrating.value) return

    const normalizedBovinCode = form.code.trim()
    const normalizedBovinLabel = form.label.trim()


    const basePayload = {
        label: normalizedBovinLabel,
        code: normalizedBovinCode

    }

    isLoading.value = true
    try {
        if (isEdit.value && idBovin.value !== null) {
            await updateBovin(idBovin.value, basePayload)
        } else {
            await createBovin(basePayload)
        }
        await navigate()
    } finally {
        isLoading.value = false
    }
}

async function navigate(){
    return router.push("/admin/bovin/list")
}
</script>
