<template>
	<div class="category-picker">
		<NcSelect
			:model-value="selectedCategories"
			:options="options"
			multiple
			:reduce="o => o.value"
			:close-on-select="false"
			placeholder="Kategorien auswählen..."
			@update:model-value="$emit('update:modelValue', $event.map(o => o.value))"
		/>

		<div class="category-picker__create">
			<NcTextField
				:model-value="newCategoryName"
				placeholder="Neue Kategorie erstellen..."
				@update:model-value="newCategoryName = $event"
			/>
			<NcButton
				type="primary"
				:disabled="!newCategoryName"
				@click="createNewCategory"
			>
				<template #icon>
					<Plus :size="20" />
				</template>
				Erstellen
			</NcButton>
		</div>
	</div>
</template>

<script setup>
import { ref, watch } from 'vue'
import { NcSelect, NcButton } from '@nextcloud/vue'
import Plus from 'vue-material-design-icons/Plus.vue'

const props = defineProps({
	modelValue: {
		type: Array,
		default: () => [],
	},
	options: {
		type: Array,
		default: () => [],
	},
})

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

const newCategoryName = ref('')

const selectedCategories = ref([...(props.modelValue || [])])

// Keep selectedCategories in sync with modelValue
watch(() => props.modelValue, (newVal) => {
	selectedCategories.value = [...(newVal || [])]
})

function createNewCategory() {
	if (!newCategoryName.value) return
	emit('create', newCategoryName.value.trim())
	newCategoryName.value = ''
}
</script>

<style scoped>
.category-picker {
	display: flex;
	flex-direction: column;
	gap: 8px;
}

.category-picker__create {
	display: flex;
	gap: 8px;
}
</style>
