<script setup>
import { computed } from 'vue';
import { useRole } from 'src/composables/useRole';
import { useAcl } from 'src/composables/useAcl';

import VnSelect from 'src/components/common/VnSelect.vue';
const emit = defineEmits(['update:modelValue']);

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

const role = useRole();
const acl = useAcl();

const isAllowedToCreate = computed(() => {
    if ($props.acls.length) return acl.hasAny($props.acls);
    return role.hasAny($props.rolesAllowedToCreate);
});
</script>
<template>
    <VnSelect
        v-model="value"
        v-bind="$attrs"
        @update:model-value="(...args) => emit('update:modelValue', ...args)"
    >
        <template v-if="isAllowedToCreate" #append>
            <QIcon
                :data-cy="$attrs.dataCy ?? $attrs.label + '_icon'"
                @click.stop.prevent="$refs.dialog.show()"
                :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 ref="dialog" 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>
    </VnSelect>
</template>
<style lang="scss" scoped>
.default-icon {
    cursor: pointer;
    color: $primary;
    border-radius: 50px;

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