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

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

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

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

import type { DbConfigInfo } from './DbConfigSummary.vue';

const props = withDefaults(
  defineProps<{
    modelValue?: string;
    writeMode?: boolean;
  }>(),
  {
    modelValue: 'default',
    writeMode: false,
  },
);

const emit = defineEmits<{
  'update:modelValue': [value: string];
  change: [payload: Pick<DbConfigInfo, 'database' | 'dbName' | 'dbType'>];
}>();

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

async function loadOptions() {
  loading.value = true;
  try {
    options.value = await getDatabaseConfigsApi();
  } catch (error) {
    console.error('Failed to load database configs:', error);
  } finally {
    loading.value = false;
  }
}

function handleChange(value: string) {
  emit('update:modelValue', value);
  const selected = options.value.find((item) => item.db_name === value);
  emit('change', {
    dbName: value,
    dbType: selected?.db_type || 'postgresql',
    database: selected?.database || '',
  });
}

watch(
  () => props.modelValue,
  (value) => {
    if (!value) {
      emit('update:modelValue', 'default');
    }
  },
  { immediate: true },
);

onMounted(loadOptions);
</script>

<template>
  <ElFormItem
    :label="$t('ai-platform.workflow.editor.dbConnection.connectionLabel')"
  >
    <ElSelect
      :model-value="modelValue"
      :loading="loading"
      class="w-full"
      filterable
      @change="handleChange"
    >
      <ElOption
        v-for="item in options"
        :key="item.db_name"
        :label="item.display_name || item.name"
        :value="item.db_name"
      >
        <span>{{ item.display_name || item.name }}</span>
        <span class="text-muted-foreground ml-2 text-xs">({{ item.db_type }})</span>
      </ElOption>
    </ElSelect>
    <ElAlert
      v-if="writeMode && modelValue === 'default'"
      class="mt-2"
      type="warning"
      :closable="false"
      show-icon
    >
      <template #title>
        <span class="text-xs">{{
          $t('ai-platform.workflow.editor.dbConnection.defaultWriteWarning')
        }}</span>
      </template>
    </ElAlert>
  </ElFormItem>
</template>
