<template>
    <div class="form-group">
        <draggable
            v-model="images"
            tag="ul"
            handle="img"
            ghost-class="ghost"
            class="list-unstyled"
            :item-key="(element) => element"
            @end="$emit('update:modelValue', images)"
        >
            <template #item="{ element }">
                <li class="mb-4">
                    <ImageThumb :id="element" :small-size="smallSize" :big-size="bigSize" />
                    <a href="#" class="small" @click.prevent="removeFile(element)">
                        <Icon v="trash" />
                        <T>crud.remove</T>
                    </a>
                </li>
            </template>
        </draggable>
        <ImageUploader :multiple="multiple" :name="name" form :sizes="sizes" @uploaded="addFiles" />
    </div>
</template>

<script>
import draggable from 'vuedraggable';

import useDialogue from '../composables/useDialogue.ts';

export default {
    components: {
        draggable,
    },
    props: {
        modelValue: {},
        multiple: { type: Boolean },
        name: { default: 'images' },
        sizes: { default: 'all' },
        smallSize: { default: 'thumb' },
        bigSize: { default: 'big' },
    },
    emits: ['update:modelValue'],
    setup() {
        return {
            dialogue: useDialogue(),
        };
    },
    data() {
        return {
            images: this.modelValue,
        };
    },
    watch: {
        modelValue() {
            this.images = this.modelValue;
        },
    },
    methods: {
        addFiles(files) {
            this.$emit('update:modelValue', [...this.images, ...files]);
        },
        async removeFile(id) {
            await this.dialogue.confirm(this.$t('crud.removeConfirm'), 'danger');
            this.$emit('update:modelValue', this.images.filter((i) => i !== id));
        },
    },
};
</script>
