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

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

import {
  ElButton,
  ElCollapse,
  ElCollapseItem,
  ElForm,
  ElFormItem,
  ElInput,
  ElMessage,
  ElOption,
  ElSelect,
} from 'element-plus';

import { testSnowflakeConnectionApi } from '#/api/ai-platform/ai-platform';

import SmartInput from '../components/SmartInput.vue';

const props = defineProps<{ data: any; nodeId: string }>();
const emit = defineEmits(['update']);

const form = ref({
  label: 'Cortex Analyst',
  connection: {
    auth_type: 'password',
    account: '',
    user: '',
    password: '',
    private_key: '',
    private_key_path: '',
    private_key_passphrase: '',
    warehouse: '',
    database: '',
    schema: 'PUBLIC',
    role: '',
  },
  question: '',
  semantic_model_file: '',
  output_variable: 'analyst_result',
  sql_variable: 'analyst_sql',
  ...props.data,
});

const activeCollapse = ref(['connection', 'query']);

const authTypeOptions = [
  {
    label: $t('ai-platform.workflow.panels.snowflakeAnalyst.authPassword'),
    value: 'password',
  },
  {
    label: $t('ai-platform.workflow.panels.snowflakeAnalyst.authKeyPair'),
    value: 'key_pair',
  },
  {
    label: $t('ai-platform.workflow.panels.snowflakeAnalyst.authSSO'),
    value: 'externalbrowser',
  },
];

const testingConnection = ref(false);
const connectionTestResult = ref<null | {
  details?: any;
  message: string;
  success: boolean;
}>(null);

async function handleTestConnection() {
  const conn = form.value.connection;

  if (!conn.account || !conn.user || !conn.warehouse || !conn.database) {
    ElMessage.warning(
      $t('ai-platform.workflow.panels.snowflakeAnalyst.fillRequired'),
    );
    return;
  }

  if (conn.auth_type === 'password' && !conn.password) {
    ElMessage.warning(
      $t('ai-platform.workflow.panels.snowflakeAnalyst.fillPassword'),
    );
    return;
  }

  if (
    conn.auth_type === 'key_pair' &&
    !conn.private_key &&
    !conn.private_key_path
  ) {
    ElMessage.warning(
      $t('ai-platform.workflow.panels.snowflakeAnalyst.fillPrivateKey'),
    );
    return;
  }

  testingConnection.value = true;
  connectionTestResult.value = null;

  try {
    const result = await testSnowflakeConnectionApi({
      auth_type: conn.auth_type as 'externalbrowser' | 'key_pair' | 'password',
      account: conn.account,
      user: conn.user,
      password: conn.password || undefined,
      private_key: conn.private_key || undefined,
      private_key_path: conn.private_key_path || undefined,
      private_key_passphrase: conn.private_key_passphrase || undefined,
      warehouse: conn.warehouse,
      database: conn.database,
      schema: conn.schema || 'PUBLIC',
      role: conn.role || undefined,
    });

    connectionTestResult.value = result;

    if (result.success) {
      ElMessage.success(result.message);
    } else {
      ElMessage.error(result.message);
    }
  } catch (error: any) {
    connectionTestResult.value = {
      success: false,
      message:
        error.message ||
        $t('ai-platform.workflow.panels.snowflakeAnalyst.connectionFailed'),
    };
    ElMessage.error(
      error.message ||
        $t('ai-platform.workflow.panels.snowflakeAnalyst.connectionFailed'),
    );
  } finally {
    testingConnection.value = false;
  }
}

watch(
  form,
  (val) => {
    emit('update', val);
  },
  { deep: true },
);
</script>

<template>
  <ElForm label-position="top">
    <ElFormItem :label="$t('ai-platform.workflow.panels.common.nodeName')">
      <ElInput v-model="form.label" placeholder="Cortex Analyst" />
    </ElFormItem>

    <ElCollapse v-model="activeCollapse">
      <ElCollapseItem
        :title="
          $t('ai-platform.workflow.panels.snowflakeAnalyst.snowflakeConnection')
        "
        name="connection"
      >
        <div class="space-y-3 pt-2">
          <ElFormItem
            :label="
              $t('ai-platform.workflow.panels.snowflakeAnalyst.authMethod')
            "
            required
          >
            <ElSelect
              v-model="form.connection.auth_type"
              :placeholder="
                $t(
                  'ai-platform.workflow.panels.snowflakeAnalyst.selectAuthMethod',
                )
              "
            >
              <ElOption
                v-for="opt in authTypeOptions"
                :key="opt.value"
                :label="opt.label"
                :value="opt.value"
              />
            </ElSelect>
          </ElFormItem>

          <ElFormItem label="Account" required>
            <SmartInput
              v-model="form.connection.account"
              :current-node-id="nodeId"
              placeholder="xxx.snowflakecomputing.com"
            />
          </ElFormItem>

          <ElFormItem label="User" required>
            <SmartInput
              v-model="form.connection.user"
              :current-node-id="nodeId"
              :placeholder="
                $t('ai-platform.workflow.panels.snowflakeAnalyst.username')
              "
            />
          </ElFormItem>

          <!-- 密码认证 -->
          <template v-if="form.connection.auth_type === 'password'">
            <ElFormItem label="Password" required>
              <SmartInput
                v-model="form.connection.password"
                :current-node-id="nodeId"
                :placeholder="
                  $t(
                    'ai-platform.workflow.panels.snowflakeAnalyst.passwordPlaceholder',
                  )
                "
              />
            </ElFormItem>
          </template>

          <!-- 密钥对认证 -->
          <template v-if="form.connection.auth_type === 'key_pair'">
            <ElFormItem
              :label="
                $t(
                  'ai-platform.workflow.panels.snowflakeAnalyst.privateKeyContent',
                )
              "
            >
              <SmartInput
                v-model="form.connection.private_key"
                :current-node-id="nodeId"
                type="textarea"
                :rows="4"
                :placeholder="
                  $t(
                    'ai-platform.workflow.panels.snowflakeAnalyst.privateKeyPlaceholder',
                  )
                "
              />
            </ElFormItem>

            <ElFormItem
              :label="
                $t(
                  'ai-platform.workflow.panels.snowflakeAnalyst.privateKeyPath',
                )
              "
            >
              <SmartInput
                v-model="form.connection.private_key_path"
                :current-node-id="nodeId"
                placeholder="/path/to/rsa_key.p8"
              />
            </ElFormItem>

            <ElFormItem
              :label="
                $t(
                  'ai-platform.workflow.panels.snowflakeAnalyst.privateKeyPassword',
                )
              "
            >
              <SmartInput
                v-model="form.connection.private_key_passphrase"
                :current-node-id="nodeId"
                :placeholder="
                  $t(
                    'ai-platform.workflow.panels.snowflakeAnalyst.privateKeyPasswordPlaceholder',
                  )
                "
              />
            </ElFormItem>
          </template>

          <!-- 外部浏览器 SSO -->
          <template v-if="form.connection.auth_type === 'externalbrowser'">
            <div class="rounded-lg bg-blue-50 p-3 text-xs text-blue-600">
              {{ $t('ai-platform.workflow.panels.snowflakeAnalyst.ssoHint') }}
            </div>
          </template>

          <ElFormItem label="Warehouse" required>
            <SmartInput
              v-model="form.connection.warehouse"
              :current-node-id="nodeId"
              placeholder="COMPUTE_WH"
            />
          </ElFormItem>

          <ElFormItem label="Database" required>
            <SmartInput
              v-model="form.connection.database"
              :current-node-id="nodeId"
              :placeholder="
                $t('ai-platform.workflow.panels.snowflakeAnalyst.databaseName')
              "
            />
          </ElFormItem>

          <ElFormItem label="Schema">
            <SmartInput
              v-model="form.connection.schema"
              :current-node-id="nodeId"
              placeholder="PUBLIC"
            />
          </ElFormItem>

          <ElFormItem label="Role">
            <SmartInput
              v-model="form.connection.role"
              :current-node-id="nodeId"
              :placeholder="
                $t('ai-platform.workflow.panels.snowflakeAnalyst.optional')
              "
            />
          </ElFormItem>

          <!-- 测试连接按钮 -->
          <div class="mt-4 flex items-center gap-3">
            <ElButton
              type="primary"
              :loading="testingConnection"
              @click="handleTestConnection"
            >
              {{
                testingConnection
                  ? $t('ai-platform.workflow.panels.snowflakeAnalyst.testing')
                  : $t(
                      'ai-platform.workflow.panels.snowflakeAnalyst.testConnection',
                    )
              }}
            </ElButton>
            <span
              v-if="connectionTestResult"
              :class="
                connectionTestResult.success ? 'text-green-600' : 'text-red-500'
              "
              class="text-sm"
            >
              {{ connectionTestResult.message }}
            </span>
          </div>

          <!-- 连接详情 -->
          <div
            v-if="connectionTestResult?.success && connectionTestResult.details"
            class="mt-2 rounded-lg bg-green-50 p-3 text-xs text-green-700"
          >
            <div>
              Snowflake version: {{ connectionTestResult.details.version }}
            </div>
            <div>Warehouse: {{ connectionTestResult.details.warehouse }}</div>
            <div>Database: {{ connectionTestResult.details.database }}</div>
            <div>Schema: {{ connectionTestResult.details.schema }}</div>
          </div>
        </div>
      </ElCollapseItem>

      <ElCollapseItem
        :title="$t('ai-platform.workflow.panels.snowflakeAnalyst.queryConfig')"
        name="query"
      >
        <div class="space-y-3 pt-2">
          <ElFormItem
            :label="
              $t('ai-platform.workflow.panels.snowflakeAnalyst.semanticModel')
            "
            required
          >
            <SmartInput
              v-model="form.semantic_model_file"
              :current-node-id="nodeId"
              placeholder="AI_TEST.PUBLIC.CAR_AI_TEST"
            />
            <div class="text-muted-foreground mt-1 space-y-1 text-xs">
              <div>
                {{
                  $t('ai-platform.workflow.panels.snowflakeAnalyst.twoFormats')
                }}:
              </div>
              <div>
                1. <strong>Semantic View</strong>: database.schema.view_name
              </div>
              <div>
                2. <strong>Stage File</strong>: @database.schema.stage/file.yaml
              </div>
            </div>
          </ElFormItem>

          <ElFormItem
            :label="
              $t('ai-platform.workflow.panels.snowflakeAnalyst.queryQuestion')
            "
            required
          >
            <SmartInput
              v-model="form.question"
              :current-node-id="nodeId"
              type="textarea"
              :rows="4"
              :placeholder="
                $t('ai-platform.workflow.panels.snowflakeAnalyst.queryPlaceholder')
              "
            />
            <div class="text-muted-foreground mt-1 text-xs">
              {{ $t('ai-platform.workflow.panels.snowflakeAnalyst.queryHint') }}
            </div>
          </ElFormItem>
        </div>
      </ElCollapseItem>
    </ElCollapse>

    <ElFormItem
      :label="$t('ai-platform.workflow.panels.snowflakeAnalyst.resultVarName')"
      class="mt-4"
    >
      <ElInput v-model="form.output_variable" placeholder="analyst_result" />
      <div class="text-muted-foreground mt-1 text-xs">
        {{ $t('ai-platform.workflow.panels.snowflakeAnalyst.resultVarHint') }}
      </div>
    </ElFormItem>

    <ElFormItem
      :label="$t('ai-platform.workflow.panels.snowflakeAnalyst.sqlVarName')"
      class="mt-2"
    >
      <ElInput v-model="form.sql_variable" placeholder="analyst_sql" />
      <div class="text-muted-foreground mt-1 text-xs">
        {{ $t('ai-platform.workflow.panels.snowflakeAnalyst.sqlVarHint') }}
      </div>
    </ElFormItem>
  </ElForm>
</template>
