<script setup>
import { ref, inject } from 'vue';
import { useI18n } from 'vue-i18n';

import VnInput from 'src/components/common/VnInput.vue';

import useNotify from 'src/composables/useNotify.js';

const props = defineProps({
    schema: {
        type: String,
        default: ''
    },
    imageName: {
        type: String,
        default: ''
    }
});

const emit = defineEmits(['close']);

const api = inject('api');
const { t } = useI18n();
const { notify } = useNotify();

const inputFileRef = ref(null);

const loading = ref(false);
const name = ref(props.imageName ?? '');
const file = ref(null);

const onSubmit = async () => {
    try {
        loading.value = true;
        const formData = new FormData();
        formData.append('name', name.value);
        formData.append('image', file.value);
        formData.append('schema', props.schema);
        formData.append('srv', 'json:image/upload');
        await api({
            method: 'post',
            url: location.origin,
            data: formData,
            headers: {
                'Content-Type': 'multipart/form-data'
            }
        });
        notify(t('imageAdded'), 'positive');
        emit('close');
    } catch (error) {
        console.error('Error uploading image:', error);
    } finally {
        loading.value = false;
    }
};
</script>

<template>
    <QForm @submit="onSubmit">
        <QCard class="q-pa-lg">
            <VnInput v-model="name" :label="t('name')" />
            <QFile
                ref="inputFileRef"
                :label="t('file')"
                v-model="file"
                :multiple="false"
                class="q-mb-xs"
            >
                <template #append>
                    <QIcon
                        name="attach_file"
                        class="cursor-pointer"
                        @click="inputFileRef.pickFiles()"
                    />
                </template>
            </QFile>
            <div class="flex row justify-end q-gutter-x-sm">
                <QSpinner
                    v-if="loading"
                    color="primary"
                    size="3em"
                    :thickness="2"
                />
                <QBtn
                    v-else
                    type="submit"
                    :label="t('send')"
                    flat
                    class="q-mt-md"
                    rounded
                />
            </div>
        </QCard>
    </QForm>
</template>

<style lang="scss" scoped></style>

<i18n lang="yaml">
en-US:
    name: Name
    file: File
    imageAdded: Image added successfully
es-ES:
    name: Nombre
    file: Archivo
    imageAdded: Imagen añadida correctamente
ca-ES:
    name: Nom
    file: Arxiu
    imageAdded: Imatge afegida correctament
fr-FR:
    name: Nom
    file: Fichier
    imageAdded: Image ajoutée correctement
pt-PT:
    name: Nome
    file: Arquivo
    imageAdded: Imagen adicionada corretamente
</i18n>
