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

defineOptions({ inheritAttrs: false })

type Option = { value: string | number; label: string }

const props = withDefaults(
  defineProps<{
    modelValue?: string | number | null
    options: Option[]
    label?: string
    placeholder?: string
    disabled?: boolean
  }>(),
  {
    label: '',
    placeholder: '',
    disabled: false,
  },
)

const emit = defineEmits<{ 'update:modelValue': [string | number] }>()
const attrs = useAttrs()
const uid = `select-${Math.random().toString(36).slice(2, 9)}`

const selectId = computed(() => (attrs.id as string) || uid)

const selectClasses = computed(() => [
  'input-magic w-full px-4 py-3 rounded-xl text-gray-700 focus:outline-none',
  props.disabled ? 'opacity-60 cursor-not-allowed' : '',
])

const passthroughAttrs = computed(() => {
  const { class: _class, id: _id, ...rest } = attrs
  return rest
})

function handleChange(event: Event) {
  const value = (event.target as HTMLSelectElement).value
  const matched = props.options.find(option => String(option.value) === value)
  emit('update:modelValue', matched ? matched.value : value)
}
</script>

<template>
  <div class="space-y-2">
    <label v-if="props.label" :for="selectId" class="text-sm font-medium text-gray-700">
      {{ props.label }}
    </label>
    <select
      :id="selectId"
      :value="props.modelValue ?? ''"
      :disabled="props.disabled"
      :class="[selectClasses, attrs.class]"
      v-bind="passthroughAttrs"
      @change="handleChange"
    >
      <option v-if="props.placeholder" value="">
        {{ props.placeholder }}
      </option>
      <option v-for="option in props.options" :key="option.value" :value="option.value">
        {{ option.label }}
      </option>
    </select>
  </div>
</template>
