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

const props = defineProps({
    modelValue: {
        type: Array,
        default: () => []
    },
    label: {
        type: String,
        default: ''
    },
    placeholder: {
        type: String,
        default: 'Введите значение и нажмите Enter'
    },
    max: {
        type: Number,
        default: 5
    },
    error: {
        type: String,
        default: null
    }
});

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

const inputValue = ref('');

const addTag = () => {
    const value = inputValue.value.trim();
    if (!value) return;
    if (props.modelValue.includes(value)) return;
    if (props.modelValue.length >= props.max) return;

    emit('update:modelValue', [...props.modelValue, value]);
    inputValue.value = '';
};

const remove = (index) => {
    const newValue = [...props.modelValue];
    newValue.splice(index, 1);
    emit('update:modelValue', newValue);
};
</script>

<template>
    <div class="field md:col-span-2 space-y-1">
        <label class="text-xs font-medium text-surface-600 dark:text-surface-300">{{ label }}</label>
        <div class="rounded-lg border border-surface-200 bg-surface-0 px-3 py-2 shadow-sm dark:border-surface-700 dark:bg-surface-950">
            <div class="flex flex-wrap gap-1">
                <Tag v-for="(item, index) in modelValue" :key="index" :value="item" severity="info" class="cursor-pointer" @click="remove(index)" />
                <div class="flex items-center gap-1 flex-1">
                    <input
                        v-model="inputValue"
                        type="text"
                        :placeholder="placeholder"
                        class="min-w-[120px] flex-1 border-0 bg-transparent text-xs text-surface-900 placeholder:text-surface-400 focus:outline-none focus:ring-0 dark:text-surface-100"
                        @keydown.enter.prevent="addTag"
                    />
                    <Button icon="pi pi-plus" size="small" text rounded :disabled="!inputValue.trim() || modelValue.length >= max" @click="addTag" v-tooltip.top="'Добавить'" />
                </div>
            </div>
        </div>
        <small v-if="error" class="p-error">{{ error }}</small>
    </div>
</template>
