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

import { Plus, Trash2 } from '@vben/icons';
import { $t } from '@vben/locales';

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

import { getActiveModelsApi } 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: $t('ai-platform.workflow.panels.intent.label'),
  model_id: '',
  model_name: '',
  input_variable: 'user_input',
  intents: [] as Array<{
    branch_id: string;
    description: string;
    examples: string[];
    name: string;
  }>,
  confidence_threshold: 0.6,
  output_variable: 'intent_result',
  ...props.data,
});

const models = ref<any[]>([]);
const activeCollapse = ref(['basic']);
const newExample = ref<Record<number, string>>({});

// 查找并更新模型名称
const updateModelName = (id: string) => {
  const model = models.value.find((m) => m.id === id);
  if (model) {
    form.value.model_name = model.model_name;
  }
};

onMounted(async () => {
  try {
    const res = await getActiveModelsApi();
    models.value = res.filter((m) => m.model_type === 'chat');
    if (form.value.model_id && !form.value.model_name) {
      updateModelName(form.value.model_id);
    }
  } catch (error) {
    console.error(error);
  }

  // 初始化至少一个意图
  if (form.value.intents.length === 0) {
    addIntent();
  }
});

watch(
  () => form.value.model_id,
  (newId) => {
    updateModelName(newId);
  },
);

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

const addIntent = () => {
  const index = form.value.intents.length + 1;
  form.value.intents.push({
    name: `intent_${index}`,
    description: '',
    examples: [],
    branch_id: `intent_${index}`,
  });
};

const removeIntent = (index: number) => {
  form.value.intents.splice(index, 1);
};

const addExample = (intentIndex: number) => {
  const example = newExample.value[intentIndex]?.trim();
  if (example) {
    form.value.intents[intentIndex].examples.push(example);
    newExample.value[intentIndex] = '';
  }
};

const removeExample = (intentIndex: number, exampleIndex: number) => {
  form.value.intents[intentIndex].examples.splice(exampleIndex, 1);
};
</script>

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

    <ElFormItem :label="$t('ai-platform.workflow.panels.common.model')">
      <ElSelect
        v-model="form.model_id"
        placeholder="{{ $t('ai-platform.workflow.panels.intent.selectModelHint') }}"
      >
        <ElOption
          v-for="m in models"
          :key="m.id"
          :label="m.model_name"
          :value="m.id"
        />
      </ElSelect>
      <div class="text-muted-foreground mt-1 text-xs">
        {{ $t('ai-platform.workflow.panels.intent.modelHint') }}
      </div>
    </ElFormItem>

    <ElFormItem :label="$t('ai-platform.workflow.panels.intent.inputVariable')">
      <SmartInput
        v-model="form.input_variable"
        :current-node-id="nodeId"
        placeholder="user_input"
      />
      <div class="text-muted-foreground mt-1 text-xs">
        {{ $t('ai-platform.workflow.panels.intent.inputVarHint') }}
        <code v-pre>{{ variable }}</code>
      </div>
    </ElFormItem>

    <!-- 意图列表 -->
    <div class="mb-4">
      <div class="mb-2 flex items-center justify-between">
        <span class="text-foreground text-sm font-medium">{{
          $t('ai-platform.workflow.panels.intent.intentList')
        }}</span>
        <ElButton link type="primary" :icon="Plus" @click="addIntent">
          {{ $t('ai-platform.workflow.panels.intent.addIntent') }}
        </ElButton>
      </div>

      <div class="space-y-3">
        <div
          v-for="(intent, index) in form.intents"
          :key="index"
          class="relative rounded-lg border border-purple-200 bg-purple-50/50 p-3"
        >
          <div class="mb-2 flex items-center justify-between">
            <span class="text-xs font-bold text-purple-600">
              {{ $t('ai-platform.workflow.panels.intent.intentLabel') }}
              {{ index + 1 }}
            </span>
            <ElButton
              v-if="form.intents.length > 1"
              link
              type="danger"
              :icon="Trash2"
              @click="removeIntent(index)"
            />
          </div>

          <div class="space-y-2">
            <ElInput
              v-model="intent.name"
              :placeholder="
                $t('ai-platform.workflow.panels.intent.intentNamePlaceholder')
              "
              size="small"
            >
              <template #prepend>
                {{ $t('ai-platform.workflow.panels.intent.name') }}
              </template>
            </ElInput>

            <ElInput
              v-model="intent.description"
              :placeholder="
                $t('ai-platform.workflow.panels.intent.intentDescPlaceholder')
              "
              size="small"
            >
              <template #prepend>
                {{ $t('ai-platform.workflow.panels.intent.description') }}
              </template>
            </ElInput>

            <ElInput
              v-model="intent.branch_id"
              :placeholder="
                $t('ai-platform.workflow.panels.intent.branchIdPlaceholder')
              "
              size="small"
            >
              <template #prepend>
                {{ $t('ai-platform.workflow.panels.intent.branchLabel') }}
              </template>
            </ElInput>

            <!-- 示例列表 -->
            <div class="mt-2 rounded border border-purple-100 bg-white p-2">
              <div class="text-muted-foreground mb-1 text-[10px] font-medium">
                {{ $t('ai-platform.workflow.panels.intent.exampleSentences') }}
              </div>

              <div
                v-if="intent.examples.length > 0"
                class="mb-2 flex flex-wrap gap-1"
              >
                <ElTag
                  v-for="(example, eIdx) in intent.examples"
                  :key="eIdx"
                  size="small"
                  closable
                  type="info"
                  @close="removeExample(index, eIdx)"
                >
                  {{ example }}
                </ElTag>
              </div>

              <div class="flex gap-1">
                <ElInput
                  v-model="newExample[index]"
                  size="small"
                  :placeholder="
                    $t('ai-platform.workflow.panels.intent.examplePlaceholder')
                  "
                  @keyup.enter="addExample(index)"
                />
                <ElButton
                  size="small"
                  type="primary"
                  :icon="Plus"
                  @click="addExample(index)"
                />
              </div>
            </div>
          </div>
        </div>

        <!-- OTHER 分支提示 -->
        <div
          class="border-border bg-muted text-muted-foreground rounded border p-3 text-center text-xs"
        >
          {{ $t('ai-platform.workflow.panels.intent.otherBranch') }}
        </div>
      </div>
    </div>

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

    <ElCollapse v-model="activeCollapse">
      <ElCollapseItem
        :title="$t('ai-platform.workflow.panels.common.advancedSettings')"
        name="advanced"
      >
        <div class="space-y-4 pt-2">
          <ElFormItem
            :label="
              $t('ai-platform.workflow.panels.intent.confidenceThreshold')
            "
          >
            <div class="flex items-center gap-4">
              <ElSlider
                v-model="form.confidence_threshold"
                :min="0"
                :max="1"
                :step="0.05"
                class="flex-1"
              />
              <ElInputNumber
                v-model="form.confidence_threshold"
                :min="0"
                :max="1"
                :step="0.05"
                size="small"
                style="width: 80px"
              />
            </div>
            <div class="text-muted-foreground mt-1 text-xs">
              {{ $t('ai-platform.workflow.panels.intent.confidenceHint') }}
            </div>
          </ElFormItem>
        </div>
      </ElCollapseItem>
    </ElCollapse>
  </ElForm>
</template>
