<script setup lang="ts">
import type { Option } from '@bagelink/vue'
import { Btn, Icon, resolveI18n } from '@bagelink/vue'
import { getOptionIcon, getOptionLabel, getOptionValue } from '../../../utils/options'

const props = withDefaults(
	defineProps<{
		options: Option[]
		label?: string
		required?: boolean
		error?: string
		thin?: boolean
		outline?: boolean
		multiselect?: boolean
	}>(),
	{ multiselect: false },
)

const selected = defineModel<string | number | (string | number)[] | null>('modelValue', { default: null })

function toggleOption(val: string | number) {
	if (props.multiselect) {
		const current = Array.isArray(selected.value) ? selected.value : []
		const idx = current.indexOf(val)
		selected.value = idx > -1 ? current.filter(v => v !== val) : [...current, val]
	} else {
		selected.value = selected.value === val ? null : val
	}
}

function isSelected(val: string | number) {
	return Array.isArray(selected.value) ? selected.value.includes(val) : selected.value === val
}
</script>

<template>
	<div class="bagel-input SelectBtn">
		<label v-if="label || required" class="pb-025">
			{{ resolveI18n(label) }}<span v-if="required"> *</span>
		</label>
		<div class="flex flex-wrap gap-05">
			<Btn
				v-for="option in options" :key="String(getOptionValue(option))" :thin="thin" :outline="outline"
				type="button" :class="isSelected(getOptionValue(option)!) ? 'primary color-white' : 'bg-transparent'"
				:style="{ color: 'var(--bgl-border-color)' }" class="border px-075 radius-2"
				@click="toggleOption(getOptionValue(option)!)"
			>
				<Icon v-if="getOptionIcon(option)" :icon="getOptionIcon(option)!" weight="300" />
				<p>{{ getOptionLabel(option) }}</p>
			</Btn>
		</div>
		<p v-if="error" class="txt-12 color-error mt-025">
			{{ error }}
		</p>
	</div>
</template>

<style scoped>
.SelectBtn {
	--btn-height: 30px;
}
</style>
