<template>
  <kuc-text
    v-if="type == 'kuc-text'"
    :value="modelValue"
    @change="updateValue"
    :disabled="selectedAppData.loading == undefined ? false : selectedAppData.loading"
  />
  <kuc-combobox
    v-else-if="type == 'kuc-combobox'"
    :value="modelValue"
    @change="updateValue"
    :disabled="selectedAppData.loading == undefined ? false : selectedAppData.loading"
  />
  <kuc-time-picker
    v-else-if="type == 'kuc-time'"
    :value="modelValue"
    @change="updateValue"
    :disabled="selectedAppData.loading == undefined ? false : selectedAppData.loading"
  />
  <!-- <table-condition-value-date-time
    v-else-if="type == 'time'|type == 'date"
    :value="modelValue"
    @change="updateValue"
    :disabled="selectedAppData.loading == undefined ? false : selectedAppData.loading"
  /> -->
</template>

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

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

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

const type = computed(() => {
  const field = getFieldObj(whereCondition.value?.field || '', props.selectedAppData.appFields, '');
  return getComponent(whereCondition.value?.condition || '', field);
});

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

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

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