<script setup lang="ts">
import type { Option } from '@bagelink/vue'

import { onMounted, watch } from 'vue'

const props = withDefaults(
	defineProps<{
		options?: Option[]
		modelValue?: any
		id?: string
		label?: string
	}>(),
	{
		modelValue: '',
		id: () => `radio-pill-${Math.random().toString(36).slice(2, 9)}`,
		label: '',
	},
)

const emits = defineEmits(['update:modelValue'])

function getLabel(option: Option) {
	if (typeof option === 'string') return option
	if (typeof option === 'number') return `${option}`
	if (typeof option === 'boolean') return option ? 'Yes' : 'No'
	return option.label
}

function getValue(option: Option) {
	if (typeof option === 'string') return option
	if (typeof option === 'number') return option
	if (typeof option === 'boolean') return option ? 'Yes' : 'No'
	return option.value
}

let selectedValue = $ref(props.modelValue)

function handleSelect(e: Event) {
	const newVal = (e.target as any)?.value
	emits('update:modelValue', newVal)
	selectedValue = newVal
}

watch(
	() => props.modelValue,
	(newVal, oldVal) => {
		if (newVal === oldVal || oldVal === undefined) return
		if (selectedValue !== newVal) selectedValue = newVal
	},
	{ immediate: true },
)

onMounted(() => {
	selectedValue = props.modelValue
})
</script>

<template>
	<div class="bagel-input">
		<label class="pb-025"> {{ label }}</label>
		<div class="flex gap-05 flex-wrap">
			<div v-for="(option, index) in options" :key="index" class="radio-pill">
				<input
					:id="`${id}-${getValue(option)}`"
					type="radio"
					:name="id"
					:value="getValue(option)"
					:checked="selectedValue === getValue(option)"
					@change="handleSelect"
				>
				<label :for="`${id}-${getValue(option)}`">{{ getLabel(option) }}</label>
			</div>
		</div>
	</div>
</template>

<style scoped>
.radio-pill label {
	color: var(--bgl-primary);
	white-space: nowrap;
	border-radius: calc(var(--btn-border-radius) * 2);
	outline: 1px solid var(--bgl-primary);
	padding-left: calc(var(--btn-padding) / 2);
	padding-right: calc(var(--btn-padding) / 2);
	padding-top: calc(var(--btn-padding) / 6);
	padding-bottom: calc(var(--btn-padding) / 6);
	cursor: pointer;
	transition: var(--bgl-transition);
	background: var(--bgl-light-text);
	user-select: none;
}

.radio-pill label:hover {
	filter: var(--bgl-hover-filter);
}

.radio-pill input {
	display: none;
}

.radio-pill input:checked ~ label {
	background: var(--bgl-primary);
	color: var(--bgl-light-text);
}
</style>
