<template>
    <MalioDrawer v-model="open" drawer-class="max-w-md">
        <template #header>
            <h2 class="text-xl font-bold">{{ $t('absences.admin.adjust.title') }}</h2>
        </template>
        <div v-if="balance" class="flex flex-col gap-4">
            <p class="text-sm text-neutral-600">
                {{ balance.user.username }} · {{ balance.label }} · {{ balance.period }}
            </p>
            <MalioInputNumber v-model="acquired" :label="$t('absences.admin.adjust.acquired')" />
            <MalioInputNumber v-model="acquiring" :label="$t('absences.admin.adjust.acquiring')" />
            <MalioInputNumber v-model="taken" :label="$t('absences.admin.adjust.taken')" />
            <div class="flex justify-end gap-2 pt-2">
                <MalioButton :label="$t('common.cancel')" variant="tertiary" @click="open = false" />
                <MalioButton :label="$t('absences.admin.adjust.save')" :disabled="submitting" @click="submit" />
            </div>
        </div>
    </MalioDrawer>
</template>

<script setup lang="ts">
import type { AbsenceBalance } from '~/modules/absence/services/dto/absence'
import { useAbsenceService } from '~/modules/absence/services/absences'

const props = defineProps<{
    modelValue: boolean
    balance: AbsenceBalance | null
}>()

const emit = defineEmits<{
    'update:modelValue': [value: boolean]
    'adjusted': []
}>()

const service = useAbsenceService()

const open = computed({
    get: () => props.modelValue,
    set: (v) => emit('update:modelValue', v),
})

// MalioInputNumber works with string values (v-model is string | null).
const acquired = ref('0')
const acquiring = ref('0')
const taken = ref('0')
const submitting = ref(false)

watch(() => props.balance, (b) => {
    acquired.value = String(b?.acquired ?? 0)
    acquiring.value = String(b?.acquiring ?? 0)
    taken.value = String(b?.taken ?? 0)
}, { immediate: true })

async function submit() {
    if (!props.balance) return
    submitting.value = true
    try {
        await service.adjustBalance(props.balance.id, {
            acquired: Number(acquired.value) || 0,
            acquiring: Number(acquiring.value) || 0,
            taken: Number(taken.value) || 0,
        })
        emit('adjusted')
        open.value = false
    } finally {
        submitting.value = false
    }
}
</script>
