<script setup>
import { ref, computed } from 'vue';

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

import { useRole } from 'src/composables/useRole';

const emit = defineEmits(['update:modelValue']);

const $props = defineProps({
    modelValue: {
        type: [String, Number, Object],
        default: null,
    },
    options: {
        type: Array,
        default: () => [],
    },
    rolesAllowedToCreate: {
        type: Array,
        default: () => ['developer'],
    },
    actionIcon: {
        type: String,
        default: 'add',
    },
    tooltip: {
        type: String,
        default: '',
    },
});

const role = useRole();
const showForm = ref(false);

const value = computed({
    get() {
        return $props.modelValue;
    },
    set(value) {
        emit('update:modelValue', value);
    },
});

const isAllowedToCreate = computed(() => {
    return role.hasAny($props.rolesAllowedToCreate);
});

const toggleForm = () => {
    showForm.value = !showForm.value;
};
</script>

<template>
    <VnSelectFilter v-model="value" :options="options" v-bind="$attrs">
        <template v-if="isAllowedToCreate" #append>
            <QIcon
                @click.stop.prevent="toggleForm()"
                :name="actionIcon"
                :size="actionIcon === 'add' ? 'xs' : 'sm'"
                :class="['default-icon', { '--add-icon': actionIcon === 'add' }]"
                :style="{
                    'font-variation-settings': `'FILL' ${1}`,
                }"
            >
                <QTooltip v-if="tooltip">{{ tooltip }}</QTooltip>
            </QIcon>
            <QDialog v-model="showForm" transition-show="scale" transition-hide="scale">
                <slot name="form" />
            </QDialog>
        </template>
        <template v-for="(_, slotName) in $slots" #[slotName]="slotData" :key="slotName">
            <slot :name="slotName" v-bind="slotData" :key="slotName" />
        </template>
    </VnSelectFilter>
</template>

<style lang="scss" scoped>
.default-icon {
    cursor: pointer;
    color: $primary;
    border-radius: 50px;

    &.--add-icon {
        color: var(--vn-text);
        background-color: $primary;
    }
}
</style>
