<template>
    <MalioDrawer v-model="open" drawer-class="max-w-md">
        <template #header>
            <h2 class="text-xl font-bold">{{ $t('absences.review.rejectTitle') }}</h2>
        </template>
        <div v-if="request" class="flex flex-col gap-4">
            <p class="text-sm text-neutral-600">
                {{ request.user.username }} · {{ request.label }} · {{ formatRange(request) }}
            </p>
            <MalioInputTextArea
                v-model="reason"
                :label="$t('absences.review.rejectReasonLabel')"
                :placeholder="$t('absences.review.rejectReasonPlaceholder')"
            />
            <div class="flex justify-end gap-2 pt-2">
                <MalioButton :label="$t('common.cancel')" variant="tertiary" @click="open = false" />
                <MalioButton
                    :label="$t('absences.review.confirm')"
                    variant="danger"
                    :disabled="!reason.trim() || submitting"
                    @click="submit"
                />
            </div>
        </div>
    </MalioDrawer>
</template>

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

const props = defineProps<{
    modelValue: boolean
    request: AbsenceRequest | null
}>()

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

const service = useAbsenceService()
const { formatRange } = useAbsenceHelpers()

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

const reason = ref('')
const submitting = ref(false)

watch(open, (v) => {
    if (v) reason.value = ''
})

async function submit() {
    if (!props.request || !reason.value.trim()) return
    submitting.value = true
    try {
        await service.reject(props.request.id, reason.value.trim())
        emit('rejected')
        open.value = false
    } finally {
        submitting.value = false
    }
}
</script>
