<script setup lang="ts">
import { computed, ref, watch } from 'vue';

import { $t } from '@vben/locales';

import { ElFormItem, ElOption, ElSelect } from 'element-plus';

import { getDatabasesApi } from '#/api/core/database-manager';

import SmartInput from './SmartInput.vue';

const props = withDefaults(
  defineProps<{
    currentNodeId?: string;
    dbName?: string;
    dbType?: string;
    modelValue?: string;
  }>(),
  {
    currentNodeId: '',
    dbName: 'default',
    dbType: 'postgresql',
    modelValue: '',
  },
);

const emit = defineEmits<{
  'update:modelValue': [value: string];
}>();

const loading = ref(false);
const options = ref<Array<{ name: string }>>([]);

const supportsDatabaseCatalog = computed(() =>
  ['postgresql', 'mysql', 'sqlserver'].includes(
    (props.dbType || 'postgresql').toLowerCase(),
  ),
);

async function loadOptions(dbName: string) {
  if (!dbName || !supportsDatabaseCatalog.value) {
    options.value = [];
    return;
  }
  loading.value = true;
  try {
    options.value = await getDatabasesApi(dbName);
  } catch (error) {
    console.error('Failed to load databases:', error);
    options.value = [];
  } finally {
    loading.value = false;
  }
}

function handleSelectChange(value: string) {
  emit('update:modelValue', value || '');
}

watch(
  () => [props.dbName, props.dbType] as const,
  ([dbName]) => {
    loadOptions(dbName || 'default');
  },
  { immediate: true },
);
</script>

<template>
  <ElFormItem
    :label="$t('ai-platform.workflow.editor.dbConnection.databaseLabel')"
  >
    <template v-if="supportsDatabaseCatalog">
      <ElSelect
        :model-value="modelValue"
        :loading="loading"
        class="mb-2 w-full"
        clearable
        filterable
        :placeholder="
          $t('ai-platform.workflow.editor.dbConnection.databasePlaceholder')
        "
        @change="handleSelectChange"
      >
        <ElOption
          v-for="item in options"
          :key="item.name"
          :label="item.name"
          :value="item.name"
        />
      </ElSelect>
      <SmartInput
        :model-value="modelValue"
        :current-node-id="currentNodeId"
        :placeholder="
          $t('ai-platform.workflow.editor.dbConnection.databaseInputPlaceholder')
        "
        @update:model-value="emit('update:modelValue', $event)"
      />
    </template>
    <SmartInput
      v-else
      :model-value="modelValue"
      :current-node-id="currentNodeId"
      :placeholder="
        $t('ai-platform.workflow.editor.dbConnection.databaseOraclePlaceholder')
      "
      @update:model-value="emit('update:modelValue', $event)"
    />
    <div class="text-muted-foreground mt-1 text-xs">
      {{
        supportsDatabaseCatalog
          ? $t('ai-platform.workflow.editor.dbConnection.databaseHint')
          : $t('ai-platform.workflow.editor.dbConnection.databaseOracleHint')
      }}
    </div>
  </ElFormItem>
</template>
