<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { RichSelect } from '@flavorly/vanilla-components'

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

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

watch(props.selected.id, (value: any) => {
  console.log('id has changed', value)
  selected.value = value
})
</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>
