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

<script setup lang="ts">
import { getEmptyOneOf, search } from '@/js/helper';
import type { OneOf } from '@/js/kintone-rest-api-client';
import type { CachedSelectedAppData, EmptyOneOf } 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, computed } from 'vue';

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

const comboboxValue = computed(() => (props.modelValue?.code || ''));

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

type EmitData = {
  obj?: any;
  value: OneOf | EmptyOneOf;
};

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

const updateValue = ({ detail }: KucEvent<ComboboxChangeEventDetail>) => {
  console.log(props.selectedAppData.appFields.fields, detail.value)
  emit('update:modelValue', {
    obj: search(props.dataList, props.id),
    value: props.selectedAppData.appFields.fields[detail.value || ''] || getEmptyOneOf(),
  });
};
</script>
