<template>
  <kuc-combobox
    v-if="items?.length"
    :items="items"
    :value="value"
    @change.stop="updateValue"
    :disabled="selectedAppData.loading == undefined ? false : selectedAppData.loading"
    className="condition-combobox-short"
    :data-val="value"
  />
</template>

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

const props = defineProps<{
  modelValue: Ref<string>;
  selectedAppData: CachedSelectedAppData;
  whereConditions: WhereCondition[];
  id: string;
}>();

const whereCondition = computed(() => search(props.whereConditions, props.id) as WhereCondition | undefined);

const items = computed(() =>
  getAvailableCondition(
    whereCondition.value?.field || '',
    props.selectedAppData.appFields,
    props.selectedAppData.table.table,
  ),
);

const value = ref(props.modelValue.value);

watch(
  () => items,
  () => {
    if (whereCondition.value?.condition === '') {
      // select first option
      const option = items.value?.[0] || { value: '' };
      value.value = option.value;
      updateValue({ detail: option });
    }
  },
  { deep: true },
);

type EmitData = {
  obj?: WhereCondition;
  value: ConditionValue;
};

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

const updateValue = ({ detail }: KucEvent<ComboboxChangeEventDetail>) => {
  value.value = detail.value || '';
  emit('update:modelValue', { obj: whereCondition.value, value: detail.value as ConditionValue });
};
</script>
