<template>
    <form :class="{ submitted }" @submit.prevent="validate">
        <div class="flex items-center justify-between relative">
            <div class="flex flex-row absolute -left-[60px]">
                <Icon
                    @click="router.push('/admin/bovin/bovin-list')"
                    name="gg:arrow-left-o"
                    size="40"
                    class="cursor-pointer text-primary-500"
                />
            </div>
            <h1 class="text-3xl text-primary-500 font-bold uppercase">
                {{ route.params.id ? 'Modifications du type bovin' : 'Ajout d\'un type bovin' }}
            </h1>
        </div>

        <div class="grid grid-cols-2 items-start pt-7 mb-8 gap-x-[200px]">
            <UiTextInput label="Nom du bovin" id="bovin-label" v-model="form.label" required />
            <UiTextInput label="Code bovin" id="code-id" v-model="form.code" required />
        </div>
        <div class="mb-11">
            <UiCheckbox v-model="form.display" label="Afficher dans les réceptions" />
        </div>
        <div class="flex justify-center items-center">
            <UiButton
                type="submit"
                :disabled="isLoading || isHydrating"
                class="inline-flex items-center justify-center text-xl min-w-[194px] text-white uppercase bg-primary-500 h-[50px] rounded hover:opacity-80 justify-self-end"
                @click="submitted = true"
            >
                Valider
            </UiButton>
        </div>
    </form>
</template>

<script setup lang="ts">
useHead({ title: 'Type de bovin' })

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

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 form = reactive<BovinFormData>({
    label: '',
    code: '',
    display: false
})


const hydrateFromBovin = (bovin: BovineTypeData | null) => {
    if (!bovin) {
        return
    }
    isHydrating.value = true
    form.label = bovin.label ?? ''
    form.code = bovin.code ?? ''
    form.display = bovin.display ?? false
    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,
        display: form.display
    }

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

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