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

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

import {
  ElButton,
  ElCollapse,
  ElCollapseItem,
  ElForm,
  ElFormItem,
  ElInput,
  ElInputNumber,
  ElMessage,
  ElOption,
  ElSelect,
  ElSlider,
} 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 LLM',
  function: 'complete',
  connection: {
    auth_type: 'password',
    account: '',
    user: '',
    password: '',
    private_key: '',
    private_key_path: '',
    private_key_passphrase: '',
    warehouse: '',
    database: '',
    schema: 'PUBLIC',
    role: '',
  },
  complete: {
    model: 'mistral-large',
    prompt: '',
    system_prompt: '',
    temperature: 0.7,
    max_tokens: 1024,
  },
  summarize: {
    text: '',
  },
  translate: {
    text: '',
    source_language: 'en',
    target_language: 'zh',
  },
  sentiment: {
    text: '',
  },
  extract_answer: {
    document: '',
    question: '',
  },
  output_variable: 'cortex_result',
  ...props.data,
});

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

const functionOptions = [
  {
    label: $t('ai-platform.workflow.panels.snowflakeLLM.funcComplete'),
    value: 'complete',
  },
  {
    label: $t('ai-platform.workflow.panels.snowflakeLLM.funcSummarize'),
    value: 'summarize',
  },
  {
    label: $t('ai-platform.workflow.panels.snowflakeLLM.funcTranslate'),
    value: 'translate',
  },
  {
    label: $t('ai-platform.workflow.panels.snowflakeLLM.funcSentiment'),
    value: 'sentiment',
  },
  {
    label: $t('ai-platform.workflow.panels.snowflakeLLM.funcExtractAnswer'),
    value: 'extract_answer',
  },
];

const modelOptions = [
  { label: 'Mistral Large', value: 'mistral-large' },
  { label: 'Mistral Large 2', value: 'mistral-large2' },
  { label: 'Mistral 7B', value: 'mistral-7b' },
  { label: 'Mixtral 8x7B', value: 'mixtral-8x7b' },
  { label: 'Llama 3 8B', value: 'llama3-8b' },
  { label: 'Llama 3 70B', value: 'llama3-70b' },
  { label: 'Llama 3.1 8B', value: 'llama3.1-8b' },
  { label: 'Llama 3.1 70B', value: 'llama3.1-70b' },
  { label: 'Llama 3.1 405B', value: 'llama3.1-405b' },
  { label: 'Llama 3.2 1B', value: 'llama3.2-1b' },
  { label: 'Llama 3.2 3B', value: 'llama3.2-3b' },
  { label: 'Snowflake Arctic', value: 'snowflake-arctic' },
  { label: 'Reka Core', value: 'reka-core' },
  { label: 'Reka Flash', value: 'reka-flash' },
  { label: 'Jamba Instruct', value: 'jamba-instruct' },
  { label: 'Jamba 1.5 Mini', value: 'jamba-1.5-mini' },
  { label: 'Jamba 1.5 Large', value: 'jamba-1.5-large' },
  { label: 'Gemma 7B', value: 'gemma-7b' },
];

const languageOptions = [
  { label: $t('ai-platform.workflow.panels.snowflakeLLM.langEn'), value: 'en' },
  { label: $t('ai-platform.workflow.panels.snowflakeLLM.langZh'), value: 'zh' },
  { label: $t('ai-platform.workflow.panels.snowflakeLLM.langJa'), value: 'ja' },
  { label: $t('ai-platform.workflow.panels.snowflakeLLM.langKo'), value: 'ko' },
  { label: $t('ai-platform.workflow.panels.snowflakeLLM.langFr'), value: 'fr' },
  { label: $t('ai-platform.workflow.panels.snowflakeLLM.langDe'), value: 'de' },
  { label: $t('ai-platform.workflow.panels.snowflakeLLM.langEs'), value: 'es' },
  { label: $t('ai-platform.workflow.panels.snowflakeLLM.langRu'), value: 'ru' },
  { label: $t('ai-platform.workflow.panels.snowflakeLLM.langPt'), value: 'pt' },
  { label: $t('ai-platform.workflow.panels.snowflakeLLM.langIt'), value: 'it' },
];

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 LLM" />
    </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.snowflakeLLM.passwordPlaceholder',
                  ) + ' {{env.SNOWFLAKE_PASSWORD}}'
                "
              />
            </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',
                  )
                "
              />
              <div class="text-muted-foreground mt-1 text-xs">
                {{ $t('ai-platform.workflow.panels.snowflakeLLM.varRefHint') }}
                {<!-- -->{ env.SNOWFLAKE_PRIVATE_KEY }}
              </div>
            </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">
              External Browser SSO
              {{ $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.snowflakeLLM.functionConfig')"
        name="function"
      >
        <div class="space-y-3 pt-2">
          <ElFormItem
            :label="$t('ai-platform.workflow.panels.snowflakeLLM.functionType')"
            required
          >
            <ElSelect
              v-model="form.function"
              :placeholder="
                $t('ai-platform.workflow.panels.snowflakeLLM.selectFunction')
              "
            >
              <ElOption
                v-for="opt in functionOptions"
                :key="opt.value"
                :label="opt.label"
                :value="opt.value"
              />
            </ElSelect>
          </ElFormItem>

          <!-- COMPLETE 配置 -->
          <template v-if="form.function === 'complete'">
            <ElFormItem :label="$t('ai-platform.workflow.panels.common.model')">
              <ElSelect
                v-model="form.complete.model"
                :placeholder="
                  $t('ai-platform.workflow.panels.common.selectModel')
                "
              >
                <ElOption
                  v-for="opt in modelOptions"
                  :key="opt.value"
                  :label="opt.label"
                  :value="opt.value"
                />
              </ElSelect>
            </ElFormItem>

            <ElFormItem>
              <template #label>
                <div class="flex items-center gap-2">
                  <span>{{
                    $t('ai-platform.workflow.panels.snowflakeLLM.systemPrompt')
                  }}</span>
                  <span class="text-muted-foreground text-xs">{{
                    $t('ai-platform.workflow.panels.llm.optional')
                  }}</span>
                </div>
              </template>
              <SmartInput
                v-model="form.complete.system_prompt"
                :current-node-id="nodeId"
                type="textarea"
                :rows="3"
                :placeholder="
                  $t(
                    'ai-platform.workflow.panels.snowflakeLLM.systemPromptPlaceholder',
                  )
                "
              />
            </ElFormItem>

            <ElFormItem
              :label="$t('ai-platform.workflow.panels.snowflakeLLM.prompt')"
              required
            >
              <SmartInput
                v-model="form.complete.prompt"
                :current-node-id="nodeId"
                type="textarea"
                :rows="4"
                :placeholder="
                  $t('ai-platform.workflow.panels.snowflakeLLM.promptPlaceholder') +
                  ' {{user_input}}'
                "
              />
            </ElFormItem>

            <ElFormItem label="Temperature">
              <div class="flex items-center gap-4">
                <ElSlider
                  v-model="form.complete.temperature"
                  :min="0"
                  :max="1"
                  :step="0.1"
                  class="flex-1"
                />
                <ElInputNumber
                  v-model="form.complete.temperature"
                  :min="0"
                  :max="1"
                  :step="0.1"
                  size="small"
                  style="width: 80px"
                />
              </div>
            </ElFormItem>

            <ElFormItem label="Max Tokens">
              <ElInputNumber
                v-model="form.complete.max_tokens"
                :min="1"
                :max="8192"
                style="width: 100%"
              />
            </ElFormItem>
          </template>

          <!-- SUMMARIZE 配置 -->
          <template v-if="form.function === 'summarize'">
            <ElFormItem
              :label="
                $t('ai-platform.workflow.panels.snowflakeLLM.summarizeText')
              "
              required
            >
              <SmartInput
                v-model="form.summarize.text"
                :current-node-id="nodeId"
                type="textarea"
                :rows="6"
                :placeholder="
                  $t(
                    'ai-platform.workflow.panels.snowflakeLLM.summarizePlaceholder',
                  )
                "
              />
            </ElFormItem>
          </template>

          <!-- TRANSLATE 配置 -->
          <template v-if="form.function === 'translate'">
            <ElFormItem
              :label="
                $t('ai-platform.workflow.panels.snowflakeLLM.translateText')
              "
              required
            >
              <SmartInput
                v-model="form.translate.text"
                :current-node-id="nodeId"
                type="textarea"
                :rows="4"
                :placeholder="
                  $t(
                    'ai-platform.workflow.panels.snowflakeLLM.translatePlaceholder',
                  )
                "
              />
            </ElFormItem>

            <div class="flex gap-4">
              <ElFormItem
                :label="
                  $t('ai-platform.workflow.panels.snowflakeLLM.sourceLanguage')
                "
                class="flex-1"
              >
                <ElSelect v-model="form.translate.source_language">
                  <ElOption
                    v-for="opt in languageOptions"
                    :key="opt.value"
                    :label="opt.label"
                    :value="opt.value"
                  />
                </ElSelect>
              </ElFormItem>

              <ElFormItem
                :label="
                  $t('ai-platform.workflow.panels.snowflakeLLM.targetLanguage')
                "
                class="flex-1"
              >
                <ElSelect v-model="form.translate.target_language">
                  <ElOption
                    v-for="opt in languageOptions"
                    :key="opt.value"
                    :label="opt.label"
                    :value="opt.value"
                  />
                </ElSelect>
              </ElFormItem>
            </div>
          </template>

          <!-- SENTIMENT 配置 -->
          <template v-if="form.function === 'sentiment'">
            <ElFormItem
              :label="
                $t('ai-platform.workflow.panels.snowflakeLLM.sentimentText')
              "
              required
            >
              <SmartInput
                v-model="form.sentiment.text"
                :current-node-id="nodeId"
                type="textarea"
                :rows="4"
                :placeholder="
                  $t(
                    'ai-platform.workflow.panels.snowflakeLLM.sentimentPlaceholder',
                  )
                "
              />
            </ElFormItem>
            <div class="text-muted-foreground text-xs">
              {{
                $t('ai-platform.workflow.panels.snowflakeLLM.sentimentRange')
              }}
            </div>
          </template>

          <!-- EXTRACT_ANSWER 配置 -->
          <template v-if="form.function === 'extract_answer'">
            <ElFormItem
              :label="
                $t('ai-platform.workflow.panels.snowflakeLLM.documentContent')
              "
              required
            >
              <SmartInput
                v-model="form.extract_answer.document"
                :current-node-id="nodeId"
                type="textarea"
                :rows="6"
                :placeholder="
                  $t(
                    'ai-platform.workflow.panels.snowflakeLLM.documentPlaceholder',
                  )
                "
              />
            </ElFormItem>

            <ElFormItem
              :label="$t('ai-platform.workflow.panels.snowflakeLLM.question')"
              required
            >
              <SmartInput
                v-model="form.extract_answer.question"
                :current-node-id="nodeId"
                type="textarea"
                :rows="2"
                :placeholder="
                  $t(
                    'ai-platform.workflow.panels.snowflakeLLM.questionPlaceholder',
                  )
                "
              />
            </ElFormItem>
          </template>
        </div>
      </ElCollapseItem>
    </ElCollapse>

    <ElFormItem
      :label="$t('ai-platform.workflow.panels.common.outputVarName')"
      class="mt-4"
    >
      <ElInput v-model="form.output_variable" placeholder="cortex_result" />
      <div class="text-muted-foreground mt-1 text-xs">
        {{ $t('ai-platform.workflow.panels.snowflakeLLM.outputVarHint') }}
      </div>
    </ElFormItem>
  </ElForm>
</template>
