<template>
    <div :class="['flex flex-col', wrapperClass]">
        <label
            v-if="label"
            :for="id"
            class="font-bold uppercase text-xl"
            :class="labelClass"
        >
            {{ label }}
        </label>
        <select
            :id="id"
            :value="modelValue ?? ''"
            :disabled="disabled || loading"
            v-bind="attrs"
            class="border-b border-black justify-self-start text-xl py-[6px] bg-transparent"
            :class="[
                isEmpty ? 'text-neutral-400' : 'text-black',
                disabled || loading ? 'cursor-not-allowed' : 'cursor-pointer',
                selectClass
            ]"
            @change="onChange"
        >
            <option value="" disabled class="text-neutral-400">
                {{ placeholderText }}
            </option>
            <option
                v-for="option in options"
                :key="option.value"
                :value="option.value"
                class="text-black"
            >
                {{ option.label }}
            </option>
        </select>
    </div>
</template>

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

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

defineOptions({ inheritAttrs: false })

const props = withDefaults(
    defineProps<{
        id?: string
        label?: string
        placeholder?: string
        modelValue: string | number | null | undefined
        options: SelectOption[]
        disabled?: boolean
        loading?: boolean
        wrapperClass?: string
        labelClass?: string
        selectClass?: string
    }>(),
    {
        placeholder: 'Sélectionner',
        disabled: false,
        loading: false,
        wrapperClass: '',
        labelClass: '',
        selectClass: ''
    }
)

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

const attrs = useAttrs()

const isEmpty = computed(() => props.modelValue === '' || props.modelValue === null || props.modelValue === undefined)
const placeholderText = computed(() => props.placeholder || 'Sélectionner')

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