<script setup lang="ts">
interface DataItem {
  id: any
  name: any
}

import { ref, computed, watch } from 'vue'
import { RichSelect } from '@flavorly/vanilla-components'

const props = defineProps({
  placeholder: {
    type: String,
    default: '0'
  },
  data: {
    type: Array as () => DataItem[],
    default: []
  },
  selected: {
    type: Object as () => DataItem,
    default: () => ({ id: 0, name: '' })
  }
})

const emit = defineEmits(['update:selected'])
const data = computed(() => [{ id: 0, name: props.placeholder }, ...props.data])
const selected = ref(data.value[0].id)

watch(
  () => props.selected,
  (value: any) => {
    selected.value = value.id
  }
)
</script>

<template>
  <div class="w-full">
    <RichSelect
      v-model="selected"
      :options="data"
      :clearable="false"
      valueAttribute="id"
      textAttribute="name"
      @update:modelValue="
        (value: any) =>
          emit(
            'update:selected',
            data.find((item) => item.id === value)
          )
      "
    />
  </div>
</template>
