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

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

const { shellClass, shellStyle } = useBagelInputShell(() => ({
	frame: props.frame,
	outline: props.outline,
	minWidth: props.minWidth,
	maxWidth: props.maxWidth,
	labelColor: props.labelColor,
	labelActiveColor: props.labelActiveColor,
}))
const hasValue = computed(() => {
	const v = selected.value
	return Array.isArray(v) ? v.length > 0 : v != null && v !== ''
})

type OptionValue = string | number | boolean

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

function toggleOption(val: OptionValue) {
	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: OptionValue) {
	return Array.isArray(selected.value) ? selected.value.includes(val) : selected.value === val
}
</script>

<template>
	<div
		class="bagel-input SelectBtn" :class="[shellClass, { 'has-value': hasValue }]" :style="shellStyle"
	>
		<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"
				type="button"
				:class="isSelected(getOptionValue(option)!) ? 'color-white' : 'bg-transparent'"
				:style="isSelected(getOptionValue(option)!)
					? {
						backgroundColor: 'var(--bgl-input-label-active-color, var(--bgl-primary))',
						borderColor: 'var(--bgl-input-label-active-color, var(--bgl-primary))',
						color: 'white',
					}
					: {
						color: 'var(--bgl-input-label-active-color, var(--bgl-border-color))',
						borderColor: 'var(--bgl-input-label-active-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 {
--bgl-btn-height: 30px;
}

</style>
