<script lang="ts">
	import { X } from '@lucide/svelte';
	import { flip } from 'svelte/animate';
	import type { ClassValue } from 'svelte/elements';

	import { Button } from '$lib/components/controls/button';
	import { Input } from '$lib/components/controls/input';

	let {
		disabled = false,
		value = $bindable(),
		placeholder,
		inputClass = '',
		class: className = '',
	}: {
		disabled?: boolean;
		value?: string[];
		placeholder?: string;
		inputClass?: ClassValue;
		class?: ClassValue;
	} = $props();

	let inputText = $state('');

	const addTag = () => {
		const v = inputText.trim();
		if (!v) return;
		if (value === undefined) value = [v];
		else if (!value.includes(v)) value.push(v);
		inputText = '';
	};
</script>

<div class={className}>
	{#if value !== undefined && value.length > 0}
		<div class="mb-2 flex flex-wrap gap-1">
			{#each value as item, i (item)}
				<span
					class="inline-flex items-center gap-1 rounded-full bg-white/10 px-2 py-1 text-xs text-white/75"
					animate:flip={{ duration: 100 }}
				>
					{item}
					<button
						class="opacity-25 hover:opacity-75"
						type="button"
						onclick={() => {
							if (value !== undefined) value.splice(i, 1);
						}}
					>
						<X size={12} strokeWidth={2} />
					</button>
				</span>
			{/each}
		</div>
	{/if}
	<div class="flex w-full items-center gap-2">
		<Input
			class={inputClass}
			{disabled}
			{placeholder}
			bind:value={inputText}
			onkeydown={(e) => {
				if (e.key === 'Enter') {
					e.preventDefault();
					addTag();
				}
			}}
		/>
		<Button type="button" variant="outline" onclick={() => addTag()}>Add</Button>
	</div>
</div>
