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

const props = defineProps<{
  modelValue: number | null
  options: { id: number; name: string }[]
  placeholder?: string
}>()

const emit = defineEmits<{
  'update:modelValue': [value: number | null]
}>()

const isOpen = ref(false)
const dropdownRef = ref<HTMLElement | null>(null)

function handleClickOutside(e: MouseEvent) {
  if (dropdownRef.value && !dropdownRef.value.contains(e.target as Node)) {
    isOpen.value = false
  }
}

onMounted(() => document.addEventListener('mousedown', handleClickOutside))
onBeforeUnmount(() => document.removeEventListener('mousedown', handleClickOutside))

const selectedLabel = computed(() => {
  const selected = props.options.find((o) => o.id === props.modelValue)
  return selected?.name ?? props.placeholder ?? 'Select...'
})

function select(id: number | null) {
  emit('update:modelValue', id)
  isOpen.value = false
}
</script>

<template>
  <div ref="dropdownRef" class="relative w-full">
    <button
      type="button"
      class="w-full mt-2 border border-gray-200 focus:border-indigo-600 focus:ring-1 focus:ring-indigo-500 px-3 py-2 rounded text-gray-700 bg-white font-body-md text-left flex items-center justify-between"
      @click="isOpen = !isOpen"
    >
      <span>{{ selectedLabel }}</span>
      <svg class="w-4 h-4 text-gray-400 shrink-0" viewBox="0 0 20 20" fill="currentColor">
        <path fill-rule="evenodd" d="M5.23 7.21a.75.75 0 011.06.02L10 11.168l3.71-3.938a.75.75 0 111.08 1.04l-4.25 4.5a.75.75 0 01-1.08 0l-4.25-4.5a.75.75 0 01.02-1.06z" clip-rule="evenodd" />
      </svg>
    </button>

    <ul
      v-show="isOpen"
      class="absolute z-50 w-full mt-1 bg-white border border-gray-200 rounded-lg shadow-lg max-h-60 overflow-auto"
    >
      <li
        class="px-3 py-2 font-body-md text-sm cursor-pointer hover:bg-indigo-50 hover:text-indigo-700 transition-colors"
        :class="{ 'text-gray-400': modelValue === null }"
        @click="select(null)"
      >
        {{ placeholder ?? 'Select...' }}
      </li>
      <li
        v-for="option in options"
        :key="option.id"
        class="px-3 py-2 font-body-md text-sm cursor-pointer hover:bg-indigo-50 hover:text-indigo-700 transition-colors"
        :class="{ 'bg-indigo-50 text-indigo-700 font-medium': option.id === modelValue }"
        @click="select(option.id)"
      >
        {{ option.name }}
      </li>
    </ul>
  </div>
</template>
