<template>
    <div :class="['flex flex-col', wrapperClass]">
        <label
            v-if="label"
            class="font-bold uppercase text-xl text-primary-500"
            :class="labelClass"
        >
            {{ label }}
        </label>
        <div
            role="radiogroup"
            :aria-label="label || id || 'radio-group'"
            :class="['flex items-center gap-6 mt-1', groupClass]"
        >
            <label
                v-for="option in options"
                :key="String(option.value)"
                :for="`${id || 'radio'}-${option.value}`"
                class="flex items-center gap-2 text-primary-500"
                :class="itemClass"
            >
                <input
                    :id="`${id || 'radio'}-${option.value}`"
                    type="radio"
                    :name="name || id || 'radio-group'"
                    :value="String(option.value)"
                    :checked="String(modelValue ?? '') === String(option.value)"
                    :disabled="disabled"
                    v-bind="attrs"
                    class="h-4 w-4 border-slate-300 text-primary-500 focus:ring-primary-500"
                    :class="[
                        disabled ? 'cursor-not-allowed' : 'cursor-pointer',
                        inputClass
                    ]"
                    @change="onChange"
                >
                <span class="text-xl" :class="optionLabelClass">
                    {{ option.label }}
                </span>
            </label>
        </div>
    </div>
</template>

<script setup lang="ts">
import { useAttrs } from 'vue'

type RadioOption = {
    value: string | number
    label: string
}

defineOptions({ inheritAttrs: false })

const props = withDefaults(
    defineProps<{
        id?: string
        name?: string
        label?: string
        modelValue: string | number | null | undefined
        options: RadioOption[]
        disabled?: boolean
        wrapperClass?: string
        labelClass?: string
        groupClass?: string
        itemClass?: string
        inputClass?: string
        optionLabelClass?: string
    }>(),
    {
        name: '',
        label: '',
        disabled: false,
        wrapperClass: '',
        labelClass: '',
        groupClass: '',
        itemClass: '',
        inputClass: '',
        optionLabelClass: ''
    }
)

const emit = defineEmits<{
    (event: 'update:modelValue', value: string): void
}>()

const attrs = useAttrs()

const onChange = (event: Event) => {
    const target = event.target as HTMLInputElement
    emit('update:modelValue', target.value)
}
</script>
