<template>
  <kuc-combobox
    className="kuc-text-input"
    :items="items.value"
    :value="modelValue.value"
    @change="updateValue"
    :key="componentKey"
    :disabled="selectedAppData.loading == undefined ? false : selectedAppData.loading"
  />
</template>

<script setup lang="ts">
import { search } from '@/js/helper';
import type { CachedSelectedAppData } from '@/types/model';
import type { KucEvent } from '@/types/my-kintone';
import type { ComboboxChangeEventDetail, DropdownItem } from 'kintone-ui-component';
import { defineProps, defineEmits, type Ref, watch, ref } from 'vue';

const props = defineProps<{
  items: Ref<DropdownItem[]>;
  modelValue: Ref<string>;
  dataList: any[];
  id: string;
  selectedAppData: CachedSelectedAppData;
}>();

const componentKey = ref(0);
// fix-bug: force select saved data when load config
watch(
  () => props.items.value,
  () => {
    if (!props.modelValue.value) return;
    componentKey.value += 1;
  },
  {
    once: true,
  },
);

type EmitData = {
  obj?: any;
  value: string;
};

const emit = defineEmits<{
  (e: 'update:modelValue', data: EmitData): void;
}>();

const updateValue = ({ detail }: KucEvent<ComboboxChangeEventDetail>) => {
  emit('update:modelValue', { obj: search(props.dataList, props.id), value: detail.value || '' });
};
</script>
