<template>
    <form @submit.prevent="validate">
    <div
        class="flex flex-col items-center gap-16">
        <div
            class="flex flex-row gap-6 items-center">
            <div
                v-for="type in bovineType"
                :key="type.id"
                class="flex flex-row mb-2 gap-6 ">
                <UiNumberInput
                    :label="type.label"
                    :code="type.code"
                    v-model="bovineQuantities[String(type.id)]"
                    :disabled="!auth.isAdmin"
                    :placeholder="0"
                    :min="0"
                    :max="10"
                />
            </div>
            <div
                class=" flex flex-row mb-2 gap-6">
                <UiNumberInput
                    label="Autres"
                    v-model="otherQuantity"
                    :disabled="!auth.isAdmin"
                />
            </div>
        </div>
        <button
            type="submit"
            class="text-xl uppercase bg-primary-500 text-white h-[50px] w-[272px]"
            :disabled="!auth.isAdmin"
        >Valider
        </button>
    </div>
    </form>
</template>
<script setup lang="ts">
import type {BovineTypeData} from "~/services/dto/bovine-type-data";
import {getBovineTypeList} from "~/services/bovine-type";
import {
    createReceptionBovine,
    deleteReceptionBovine,
    getReceptionBovineList,
    updateReceptionBovine
} from "~/services/reception-bovine";
import {computed, onMounted, reactive, ref, watch} from "vue";
import {getReception, updateReception} from "~/services/reception";
const toast = useToast()
const isLoadingBovineType = ref(false)
const bovineType = ref<BovineTypeData[]>([])
const bovineQuantities = reactive<Record<string, number | null>>({})
const otherQuantity = ref<number | null>(0)
const auth = useAuthStore()
const props = defineProps<{
    idReception: number
}>()
const receptionId = props.idReception
const reception = await getReception(receptionId)

const receptionIri = computed(() =>
    receptionId ? `/api/receptions/${receptionId}` : null
)
const totalBovines = computed(() => {
    const base = Object.values(bovineQuantities).reduce((sum, value) => {
        return sum + (value ?? 0)
    }, 0)
    return base + (otherQuantity.value ?? 0)
})

const loadBovineType = async () => {
    isLoadingBovineType.value = true
    try {
        bovineType.value = await getBovineTypeList()
    } finally {
        isLoadingBovineType.value = false
    }
}

onMounted(async () => {
    await loadBovineType()
})

watch(
    [() => receptionId, () => bovineType.value],
    async ([id, types]) => {
        if (!id || !receptionIri.value || types.length === 0) {
            return
        }

        const selectionMap: Record<string, number | null> = {}
        for (const type of types) {
            selectionMap[String(type.id)] = 0
        }

        const existing = await getReceptionBovineList(receptionIri.value)
        for (const selection of existing) {
            const bovineTypeId = String(selection.bovineType.id)
            selectionMap[bovineTypeId] = selection.quantity ?? 0
        }

        for (const key of Object.keys(bovineQuantities)) {
            delete bovineQuantities[key]
        }
        Object.assign(bovineQuantities, selectionMap)

        const existingOther = reception.bovineDetail
        const parsedOther =
            typeof existingOther === 'string' && existingOther.trim() !== ''
                ? Number(existingOther)
                : 0
        otherQuantity.value = Number.isFinite(parsedOther) ? parsedOther : 0
    },
    {immediate: true}
)

async function syncBovineSelections(receptionIri: string) {
    const existing = await getReceptionBovineList(receptionIri)
    const existingMap = new Map<string, { id: number; quantity: number | null }>()

    for (const selection of existing) {
        const bovineTypeId = String(selection.bovineType.id)
        existingMap.set(bovineTypeId, {
            id: selection.id,
            quantity: selection.quantity ?? 0
        })
    }

    // Supprime les entrées supprimées ou modifiées
    for (const [bovineTypeId, entry] of existingMap.entries()) {
        const selectedQuantity = bovineQuantities[bovineTypeId] ?? 0
        if (!selectedQuantity) {
            await deleteReceptionBovine(entry.id)
            existingMap.delete(bovineTypeId)
            continue
        }

        if (selectedQuantity !== entry.quantity) {
            await updateReceptionBovine(entry.id, {quantity: selectedQuantity})
            existingMap.set(bovineTypeId, {
                id: entry.id,
                quantity: selectedQuantity
            })
        }
    }

    // Crée les entrées manquantes
    for (const [bovineTypeId, quantity] of Object.entries(bovineQuantities)) {
        if (!quantity) {
            continue
        }
        if (existingMap.has(bovineTypeId)) {
            // Déjà à jour
            continue
        }
        await createReceptionBovine({
            reception: receptionIri,
            bovineType: `/api/bovine_types/${bovineTypeId}`,
            quantity
        })
    }
}

async function validate() {
    // @TODO Ajouter un composable pour le toaster qui gère les key i18n
    if (totalBovines.value > 52) {
        toast.error({
            title: 'Erreur',
            message: ('Le total des bovins ne peut pas dépasser 52.')
        })
        return
    }

    await syncBovineSelections(receptionIri.value)

    await updateReception(receptionId, {
        merchandiseType: null,
        merchandiseDetail: null,
        bovineDetail: otherQuantity.value ? String(otherQuantity.value) : null,
    })
}
</script>
