<template>
    <div class="flex items-center gap-3">
        <input
            ref="fileInput"
            type="file"
            class="hidden"
            @change="onFileSelected"
        >
        <MalioButton
            icon-name="mdi:paperclip"
            icon-position="left"
            button-class="w-auto px-4"
            :label="$t('directory.documents.add')"
            :disabled="uploading"
            @click="fileInput?.click()"
        />
        <span v-if="uploading" class="text-sm text-neutral-500">{{ $t('directory.documents.uploading') }}</span>
    </div>
</template>

<script setup lang="ts">
import { useReportDocumentService } from '~/modules/directory/services/report-documents'

const props = defineProps<{ reportId: number }>()
const emit = defineEmits<{ uploaded: [] }>()

const service = useReportDocumentService()
const fileInput = ref<HTMLInputElement | null>(null)
const uploading = ref(false)

async function onFileSelected(event: Event): Promise<void> {
    const input = event.target as HTMLInputElement
    const file = input.files?.[0]
    if (!file) return

    uploading.value = true
    try {
        await service.upload(props.reportId, file)
        emit('uploaded')
    } finally {
        uploading.value = false
        input.value = ''
    }
}
</script>
