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

import {
  AppWindow,
  BookOpen,
  Bot,
  ChevronDown,
  ChevronRight,
  CircleHelp,
  ClipboardCheck,
  Code,
  Combine,
  Database,
  FileText,
  Globe,
  HelpCircle,
  LayoutDashboard,
  LayoutTemplate,
  ListChecks,
  MessageSquareText,
  Play,
  Search,
  Square,
} from '@vben/icons';
import { $t } from '@vben/locales';

import { useVueFlow } from '@vue-flow/core';
import { ElInput, ElScrollbar, ElTooltip } from 'element-plus';

const props = defineProps<{
  currentNodeId: string;
}>();

const emit = defineEmits(['select']);
const { nodes, edges } = useVueFlow();

const searchQuery = ref('');
const collapsedNodes = ref<Set<string>>(new Set());

// 定义不同节点的图标
const icons: any = {
  start: Play,
  llm: Bot,
  http: Globe,
  code: Code,
  template: LayoutTemplate,
  end: Square,
  // 对话流节点
  question: HelpCircle,
  choice: ListChecks,
  message: MessageSquareText,
  confirm: CircleHelp,
  // Snowflake Cortex 节点
  // 循环节点
  loop: Play,
  // 合并节点
  merge: Combine,
  // 表单节点
  form_basic_info: FileText,
  form_database_design: Database,
  form_database_create: Database,
  // 应用节点
  app_create: AppWindow,
  app_design: LayoutDashboard,
  app_settings: LayoutDashboard,
  app_update: LayoutDashboard,
  // 仪表盘节点
  dashboard_basic_info: LayoutDashboard,
  dashboard_design: LayoutDashboard,
  dashboard_create: LayoutDashboard,
  dashboard_publish: LayoutDashboard,
  // 系统总结节点
  system_summary: ClipboardCheck,
  // 子流程节点
  subflow: Play,
  // 知识库检索节点
  knowledge_retrieval: BookOpen,
};

// 获取当前节点的父循环节点（如果存在）
const getParentLoopNode = (nodeId: string) => {
  const currentNode = nodes.value.find((n) => n.id === nodeId);
  if (currentNode?.parentNode) {
    const parentNode = nodes.value.find((n) => n.id === currentNode.parentNode);
    if (parentNode?.type === 'loop') {
      return parentNode;
    }
  }
  return null;
};

// 获取当前节点的所有上游节点（通过边的连接关系递归查找）
const getUpstreamNodeIds = (
  nodeId: string,
  visited = new Set<string>(),
): Set<string> => {
  // 找到所有指向当前节点的边
  const incomingEdges = edges.value.filter((e) => e.target === nodeId);

  for (const edge of incomingEdges) {
    const sourceId = edge.source;
    if (!visited.has(sourceId)) {
      visited.add(sourceId);
      // 递归查找上游节点的上游
      getUpstreamNodeIds(sourceId, visited);
    }
  }

  // 如果当前节点是循环体内的子节点，也要包含父循环节点及其上游节点
  const parentLoop = getParentLoopNode(nodeId);
  if (parentLoop && !visited.has(parentLoop.id)) {
    visited.add(parentLoop.id);
    // 递归查找父循环节点的上游
    getUpstreamNodeIds(parentLoop.id, visited);
  }

  return visited;
};

// 获取所有可用的前序节点（只显示上游节点）
const availableNodes = computed(() => {
  // 获取当前节点的所有上游节点 ID
  const upstreamIds = getUpstreamNodeIds(props.currentNodeId);

  // 只保留上游节点
  return nodes.value
    .filter((n) => upstreamIds.has(n.id) && n.type !== 'end')
    .map((node) => {
      let variables: any[] = [];

      // 根据节点类型获取输出变量 schema
      switch (node.type) {
        case 'app_create': {
          variables = [
            {
              key: 'app_id',
              label: $t('ai-platform.workflow.editor.variableSelector.appId'),
            },
            {
              key: 'app_code',
              label: $t('ai-platform.workflow.editor.variableSelector.appCode'),
            },
            {
              key: 'app_name',
              label: $t('ai-platform.workflow.editor.variableSelector.appName'),
            },
            {
              key: 'success',
              label: $t(
                'ai-platform.workflow.editor.variableSelector.createSuccess',
              ),
            },
          ];
          break;
        }
        case 'app_design': {
          variables = [
            {
              key: 'design_content',
              label: $t(
                'ai-platform.workflow.editor.variableSelector.designContent',
              ),
            },
            {
              key: 'design_title',
              label: $t(
                'ai-platform.workflow.editor.variableSelector.designTitle',
              ),
            },
            {
              key: 'confirmed',
              label: $t(
                'ai-platform.workflow.editor.variableSelector.isConfirmed',
              ),
            },
          ];
          break;
        }
        case 'app_settings': {
          variables = [
            {
              key: 'settings',
              label: $t(
                'ai-platform.workflow.editor.variableSelector.appSettings',
              ),
            },
            {
              key: 'confirmed',
              label: $t(
                'ai-platform.workflow.editor.variableSelector.isConfirmed',
              ),
            },
          ];
          break;
        }
        case 'app_update': {
          variables = [
            {
              key: 'update_success',
              label: $t(
                'ai-platform.workflow.editor.variableSelector.updateSuccess',
              ),
            },
            {
              key: 'config_id',
              label: $t(
                'ai-platform.workflow.editor.variableSelector.configId',
              ),
            },
            {
              key: 'update_message',
              label: $t(
                'ai-platform.workflow.editor.variableSelector.updateMessage',
              ),
            },
          ];
          break;
        }
        case 'choice': {
          const choiceVar = node.data.variable_name || 'user_choice';
          variables = [
            {
              key: choiceVar,
              label: $t(
                'ai-platform.workflow.editor.variableSelector.userChoice',
              ),
            },
            {
              key: `${choiceVar}_labels`,
              label: $t(
                'ai-platform.workflow.editor.variableSelector.choiceText',
              ),
            },
          ];
          break;
        }
        case 'code': {
          // 默认提供 result 变量
          variables = [
            {
              key: 'result',
              label: $t(
                'ai-platform.workflow.editor.variableSelector.execResult',
              ),
              isSystem: true,
            },
          ];
          // 加上用户自定义的输出变量
          const customOutputs = (node.data.outputs || [])
            .filter((v: any) => v.variable && v.variable !== 'result')
            .map((v: any) => ({
              key: v.variable,
              label: v.variable,
            }));
          variables.push(...customOutputs);
          break;
        }
        case 'condition': {
          // 条件节点不产生输出变量
          break;
        }
        case 'confirm': {
          const confirmVar = node.data.variable_name || 'confirmed';
          variables = [
            {
              key: confirmVar,
              label: $t(
                'ai-platform.workflow.editor.variableSelector.confirmed',
              ),
            },
          ];
          break;
        }
        case 'dashboard_basic_info': {
          variables = [
            {
              key: 'dashboard_basic_info',
              label: $t(
                'ai-platform.workflow.editor.variableSelector.dashboardBasicInfo',
              ),
            },
            {
              key: 'dashboard_name',
              label: $t(
                'ai-platform.workflow.editor.variableSelector.dashboardName',
              ),
            },
            {
              key: 'dashboard_code',
              label: $t(
                'ai-platform.workflow.editor.variableSelector.dashboardCode',
              ),
            },
          ];
          break;
        }
        case 'dashboard_create': {
          variables = [
            {
              key: 'dashboard_id',
              label: $t(
                'ai-platform.workflow.editor.variableSelector.dashboardId',
              ),
            },
            {
              key: 'dashboard_code',
              label: $t(
                'ai-platform.workflow.editor.variableSelector.dashboardCode',
              ),
            },
            {
              key: 'page_meta',
              label: $t(
                'ai-platform.workflow.editor.variableSelector.pageMeta',
              ),
            },
          ];
          break;
        }
        case 'dashboard_design': {
          variables = [
            {
              key: 'page_config',
              label: $t(
                'ai-platform.workflow.editor.variableSelector.pageConfig',
              ),
            },
            {
              key: 'design_title',
              label: $t(
                'ai-platform.workflow.editor.variableSelector.designTitle',
              ),
            },
            {
              key: 'confirmed',
              label: $t(
                'ai-platform.workflow.editor.variableSelector.isConfirmed',
              ),
            },
          ];
          break;
        }
        case 'dashboard_publish': {
          variables = [
            {
              key: 'menu_id',
              label: $t('ai-platform.workflow.editor.variableSelector.menuId'),
            },
            {
              key: 'route_path',
              label: $t(
                'ai-platform.workflow.editor.variableSelector.routePath',
              ),
            },
            {
              key: 'publish_result',
              label: $t(
                'ai-platform.workflow.editor.variableSelector.publishResult',
              ),
            },
          ];
          break;
        }
        case 'db_delete': {
          const deleteOutputVar = node.data.output_variable || 'delete_result';
          variables = [
            {
              key: deleteOutputVar,
              label: $t(
                'ai-platform.workflow.editor.variableSelector.deleteResult',
              ),
            },
            {
              key: `${deleteOutputVar}_count`,
              label: $t(
                'ai-platform.workflow.editor.variableSelector.affectedRows',
              ),
            },
          ];
          break;
        }
        case 'db_insert': {
          const insertOutputVar = node.data.output_variable || 'insert_result';
          variables = [
            {
              key: insertOutputVar,
              label: $t(
                'ai-platform.workflow.editor.variableSelector.insertResult',
              ),
            },
            {
              key: `${insertOutputVar}_id`,
              label: $t(
                'ai-platform.workflow.editor.variableSelector.insertId',
              ),
            },
          ];
          break;
        }
        case 'db_query': {
          const queryOutputVar = node.data.output_variable || 'query_result';
          variables = [
            {
              key: queryOutputVar,
              label: $t(
                'ai-platform.workflow.editor.variableSelector.queryResult',
              ),
            },
            {
              key: `${queryOutputVar}_count`,
              label: $t(
                'ai-platform.workflow.editor.variableSelector.resultCount',
              ),
            },
          ];
          break;
        }
        case 'db_sql': {
          const sqlOutputVar = node.data.output_variable || 'sql_result';
          variables = [
            {
              key: sqlOutputVar,
              label: $t(
                'ai-platform.workflow.editor.variableSelector.sqlResult',
              ),
            },
            {
              key: `${sqlOutputVar}_count`,
              label: $t(
                'ai-platform.workflow.editor.variableSelector.resultCount',
              ),
            },
          ];
          break;
        }
        case 'db_update': {
          const updateOutputVar = node.data.output_variable || 'update_result';
          variables = [
            {
              key: updateOutputVar,
              label: $t(
                'ai-platform.workflow.editor.variableSelector.updateResult',
              ),
            },
            {
              key: `${updateOutputVar}_count`,
              label: $t(
                'ai-platform.workflow.editor.variableSelector.affectedRows',
              ),
            },
          ];
          break;
        }
        case 'form_basic_info': {
          variables = [
            {
              key: 'form_basic_info',
              label: $t(
                'ai-platform.workflow.editor.variableSelector.formBasicInfoObj',
              ),
            },
            {
              key: 'form_name',
              label: $t(
                'ai-platform.workflow.editor.variableSelector.formName',
              ),
            },
            {
              key: 'form_code',
              label: $t(
                'ai-platform.workflow.editor.variableSelector.formCode',
              ),
            },
            {
              key: 'form_type',
              label: $t(
                'ai-platform.workflow.editor.variableSelector.formType',
              ),
            },
            {
              key: 'form_description',
              label: $t(
                'ai-platform.workflow.editor.variableSelector.formDescription',
              ),
            },
            {
              key: 'form_sort',
              label: $t(
                'ai-platform.workflow.editor.variableSelector.formSort',
              ),
            },
          ];
          break;
        }
        case 'form_create': {
          variables = [
            {
              key: 'form_id',
              label: $t('ai-platform.workflow.editor.variableSelector.formId'),
            },
            {
              key: 'form_code',
              label: $t(
                'ai-platform.workflow.editor.variableSelector.formCode',
              ),
            },
            {
              key: 'form_meta',
              label: $t(
                'ai-platform.workflow.editor.variableSelector.formMeta',
              ),
            },
          ];
          break;
        }
        case 'form_database_create': {
          variables = [
            {
              key: 'creation_result',
              label: $t(
                'ai-platform.workflow.editor.variableSelector.creationResult',
              ),
            },
            {
              key: 'all_tables_ready',
              label: $t(
                'ai-platform.workflow.editor.variableSelector.allTablesReady',
              ),
            },
            {
              key: 'created_count',
              label: $t(
                'ai-platform.workflow.editor.variableSelector.createdCount',
              ),
            },
            {
              key: 'error_count',
              label: $t(
                'ai-platform.workflow.editor.variableSelector.errorCount',
              ),
            },
            {
              key: 'schema_name',
              label: $t(
                'ai-platform.workflow.editor.variableSelector.schemaName',
              ),
            },
            {
              key: 'table_name',
              label: $t(
                'ai-platform.workflow.editor.variableSelector.tableName',
              ),
            },
          ];
          break;
        }
        case 'form_database_design': {
          variables = [
            {
              key: 'database_design',
              label: $t(
                'ai-platform.workflow.editor.variableSelector.dbDesignObj',
              ),
            },
            {
              key: 'table_name',
              label: $t(
                'ai-platform.workflow.editor.variableSelector.tableName',
              ),
            },
            {
              key: 'field_count',
              label: $t(
                'ai-platform.workflow.editor.variableSelector.fieldCount',
              ),
            },
          ];
          break;
        }
        case 'form_list_design': {
          variables = [
            {
              key: 'list_config',
              label: $t(
                'ai-platform.workflow.editor.variableSelector.listConfig',
              ),
            },
            {
              key: 'query_field_count',
              label: $t(
                'ai-platform.workflow.editor.variableSelector.queryFieldCount',
              ),
            },
            {
              key: 'column_count',
              label: $t(
                'ai-platform.workflow.editor.variableSelector.columnCount',
              ),
            },
          ];
          break;
        }
        case 'form_publish': {
          variables = [
            {
              key: 'menu_id',
              label: $t('ai-platform.workflow.editor.variableSelector.menuId'),
            },
            {
              key: 'route_path',
              label: $t(
                'ai-platform.workflow.editor.variableSelector.routePath',
              ),
            },
            {
              key: 'publish_result',
              label: $t(
                'ai-platform.workflow.editor.variableSelector.publishResult',
              ),
            },
          ];
          break;
        }
        case 'form_ui_design': {
          variables = [
            {
              key: 'form_ui_design',
              label: $t(
                'ai-platform.workflow.editor.variableSelector.formUiDesign',
              ),
            },
            {
              key: 'form_code',
              label: $t(
                'ai-platform.workflow.editor.variableSelector.formCode',
              ),
            },
            {
              key: 'field_count',
              label: $t(
                'ai-platform.workflow.editor.variableSelector.fieldCount',
              ),
            },
            {
              key: 'group_count',
              label: $t(
                'ai-platform.workflow.editor.variableSelector.groupCount',
              ),
            },
          ];
          break;
        }
        case 'http': {
          variables = [
            {
              key: 'body',
              label: $t(
                'ai-platform.workflow.editor.variableSelector.responseBody',
              ),
            },
            {
              key: 'status_code',
              label: $t(
                'ai-platform.workflow.editor.variableSelector.statusCode',
              ),
            },
          ];
          break;
        }
        case 'knowledge_retrieval': {
          // 知识库检索节点固定输出变量
          variables = [
            {
              key: 'knowledge_results',
              label: $t(
                'ai-platform.workflow.editor.variableSelector.knowledgeResults',
              ),
            },
            {
              key: 'knowledge_context',
              label: $t(
                'ai-platform.workflow.editor.variableSelector.knowledgeContext',
              ),
            },
            {
              key: 'knowledge_results_total',
              label: $t(
                'ai-platform.workflow.editor.variableSelector.knowledgeResultsTotal',
              ),
            },
          ];
          break;
        }
        case 'llm': {
          // 使用配置的输出变量名，默认为 llm_response
          const outputVar = node.data.output_variable || 'llm_response';
          const outputMode = node.data.output_mode || 'text';
          const outputSchema = node.data.output_schema || [];

          if (outputMode === 'structured' && outputSchema.length > 0) {
            // 结构化输出模式：展示每个定义的字段
            variables = [
              {
                key: outputVar,
                label: $t(
                  'ai-platform.workflow.editor.variableSelector.jsonString',
                ),
                isStructured: true,
              },
              {
                key: `${outputVar}_data`,
                label: $t(
                  'ai-platform.workflow.editor.variableSelector.structuredData',
                ),
                isStructured: true,
              },
            ];
            // 添加每个字段作为独立变量
            for (const field of outputSchema) {
              if (field.name) {
                const fieldLabel = field.description || field.name;
                const fieldType = field.type || 'string';
                variables.push({
                  key: `${outputVar}_${field.name}`,
                  label: `${fieldLabel} (${fieldType})`,
                  isField: true,
                });
              }
            }
            variables.push({
              key: `${outputVar}_tokens`,
              label: $t(
                'ai-platform.workflow.editor.variableSelector.tokenUsage',
              ),
            });
          } else {
            // 普通文本输出模式
            variables = [
              {
                key: outputVar,
                label: $t(
                  'ai-platform.workflow.editor.variableSelector.llmResponse',
                ),
              },
              {
                key: `${outputVar}_tokens`,
                label: $t(
                  'ai-platform.workflow.editor.variableSelector.tokenUsage',
                ),
              },
            ];
          }
          break;
        }
        // 循环节点
        case 'loop': {
          const itemVar = node.data.item_variable_name || 'item';
          const indexVar = node.data.index_variable_name || 'index';
          variables = [
            {
              key: itemVar,
              label: $t(
                'ai-platform.workflow.editor.variableSelector.currentLoopItem',
              ),
              isSystem: true,
            },
            {
              key: indexVar,
              label: $t(
                'ai-platform.workflow.editor.variableSelector.currentIndex',
              ),
              isSystem: true,
            },
          ];
          // 如果是 for_each 模式，还可以引用原始数组
          if (node.data.loop_mode === 'for_each') {
            const outputVar = node.data.output_variable || 'loop_results';
            variables.push({
              key: outputVar,
              label: $t(
                'ai-platform.workflow.editor.variableSelector.loopResults',
              ),
            });
          }
          break;
        }
        case 'merge': {
          const mergeOutputVar = node.data.output_variable || 'merged_result';
          variables = [
            {
              key: mergeOutputVar,
              label: $t(
                'ai-platform.workflow.editor.variableSelector.mergeResult',
              ),
            },
            {
              key: 'branch_count',
              label: $t(
                'ai-platform.workflow.editor.variableSelector.branchCount',
              ),
            },
          ];
          break;
        }
        case 'message': {
          // 消息节点不产生输出变量
          break;
        }
        case 'parallel': {
          // 并行节点不产生输出变量
          break;
        }
        // 对话流节点
        case 'question': {
          const questionVar = node.data.variable_name || 'user_input';
          variables = [
            {
              key: questionVar,
              label: $t(
                'ai-platform.workflow.editor.variableSelector.userAnswer',
              ),
            },
            {
              key: `${questionVar}_valid`,
              label: $t('ai-platform.workflow.editor.variableSelector.isValid'),
            },
          ];
          break;
        }
        case 'snowflake_cortex_analyst': {
          const analystResultVar =
            node.data.output_variable || 'analyst_result';
          const analystSqlVar = node.data.sql_variable || 'analyst_sql';
          variables = [
            {
              key: analystResultVar,
              label: $t(
                'ai-platform.workflow.editor.variableSelector.queryResultData',
              ),
            },
            {
              key: analystSqlVar,
              label: $t(
                'ai-platform.workflow.editor.variableSelector.generatedSql',
              ),
            },
            {
              key: `${analystResultVar}_raw`,
              label: $t(
                'ai-platform.workflow.editor.variableSelector.rawResponse',
              ),
            },
          ];
          break;
        }
        // Snowflake Cortex 节点
        case 'snowflake_cortex_llm': {
          const cortexLlmVar = node.data.output_variable || 'cortex_response';
          variables = [
            {
              key: cortexLlmVar,
              label: $t(
                'ai-platform.workflow.editor.variableSelector.cortexLlmResponse',
              ),
            },
          ];
          break;
        }
        case 'start': {
          // 默认的系统变量
          variables = [
            {
              key: 'user_input',
              label: $t(
                'ai-platform.workflow.editor.variableSelector.userInput',
              ),
              isSystem: true,
            },
            {
              key: 'application_id',
              label: $t('ai-platform.workflow.editor.variableSelector.appId'),
              isSystem: true,
            },
            {
              key: 'application_code',
              label: $t('ai-platform.workflow.editor.variableSelector.appCode'),
              isSystem: true,
            },
            {
              key: 'form_code',
              label: $t(
                'ai-platform.workflow.editor.variableSelector.formCode',
              ),
              isSystem: true,
            },
          ];
          // 加上自定义变量
          variables.push(
            ...(node.data.variables || []).map((v: any) => ({
              key: v.variable,
              label: v.label || v.variable,
              isSystem: false,
            })),
          );
          break;
        }
        case 'subflow': {
          const resultVar = node.data.result_variable || 'subflow_result';
          variables = [
            {
              key: resultVar,
              label: $t(
                'ai-platform.workflow.editor.variableSelector.subflowFullResult',
              ),
            },
            {
              key: `${resultVar}.success`,
              label: $t(
                'ai-platform.workflow.editor.variableSelector.execSuccess',
              ),
            },
            {
              key: `${resultVar}.outputs`,
              label: $t(
                'ai-platform.workflow.editor.variableSelector.subflowOutputVars',
              ),
            },
            {
              key: `${resultVar}.total_tokens`,
              label: $t(
                'ai-platform.workflow.editor.variableSelector.tokenUsage',
              ),
            },
          ];

          // 如果配置了结果传递，添加传递的变量
          const resultPassMode = node.data.result_pass_mode || 'all';
          if (resultPassMode === 'all') {
            // all 模式：提示所有子流程输出变量都可用
            variables.push({
              key: '*',
              label: $t(
                'ai-platform.workflow.editor.variableSelector.allSubflowVars',
              ),
              isSystem: true,
            });
          } else if (resultPassMode === 'selected') {
            // selected 模式：显示选择的变量
            const resultVars = node.data.result_vars || [];
            resultVars.forEach((varName: string) => {
              variables.push({
                key: varName,
                label: `${varName} (${$t('ai-platform.workflow.editor.variableSelector.fromSubflow')})`,
              });
            });
          }
          break;
        }
        case 'system_summary': {
          variables = [
            {
              key: 'summary',
              label: $t(
                'ai-platform.workflow.editor.variableSelector.summaryData',
              ),
            },
            {
              key: 'total_forms',
              label: $t(
                'ai-platform.workflow.editor.variableSelector.totalForms',
              ),
            },
            {
              key: 'has_app',
              label: $t('ai-platform.workflow.editor.variableSelector.hasApp'),
            },
            {
              key: 'has_dashboard',
              label: $t(
                'ai-platform.workflow.editor.variableSelector.hasDashboard',
              ),
            },
          ];
          break;
        }
        case 'template': {
          const templateOutputVar =
            node.data.output_variable || 'template_result';
          variables = [
            {
              key: templateOutputVar,
              label: $t(
                'ai-platform.workflow.editor.variableSelector.renderResult',
              ),
            },
          ];
          break;
        }
        case 'text_to_sql': {
          const textToSqlOutputVar =
            node.data.output_variable || 'text_to_sql_result';
          variables = [
            {
              key: `${textToSqlOutputVar}_sql`,
              label: $t(
                'ai-platform.workflow.editor.variableSelector.generatedSqlStatement',
              ),
            },
            {
              key: `${textToSqlOutputVar}_thought`,
              label: $t(
                'ai-platform.workflow.editor.variableSelector.sqlThought',
              ),
            },
          ];
          break;
        }
        default: {
          // 其他未知节点类型，尝试从 output_variable 获取
          if (node.data.output_variable) {
            variables = [
              {
                key: node.data.output_variable,
                label: $t(
                  'ai-platform.workflow.editor.variableSelector.output',
                ),
              },
            ];
          }
          break;
        }
      }

      return {
        id: node.id,
        label: node.data.label || node.label,
        type: node.type,
        variables,
      };
    })
    .filter((n) => n.variables.length > 0);
});

const filteredNodes = computed(() => {
  if (!searchQuery.value) return availableNodes.value;
  const query = searchQuery.value.toLowerCase();
  return availableNodes.value.filter((node) => {
    const matchNode = node.label.toLowerCase().includes(query);
    const matchVar = node.variables.some(
      (v: any) =>
        v.key.toLowerCase().includes(query) ||
        v.label.toLowerCase().includes(query),
    );
    return matchNode || matchVar;
  });
});

const toggleNodeCollapse = (nodeId: string) => {
  if (collapsedNodes.value.has(nodeId)) {
    collapsedNodes.value.delete(nodeId);
  } else {
    collapsedNodes.value.add(nodeId);
  }
};

const isNodeCollapsed = (nodeId: string) => {
  return collapsedNodes.value.has(nodeId);
};

const handleSelect = (nodeId: string, variable: string) => {
  emit('select', `{{${nodeId}.${variable}}}`);
};
</script>

<template>
  <div class="flex h-[390px] w-full flex-col rounded-lg">
    <div class="border-border bg-muted shrink-0 border-b p-2">
      <ElInput
        v-model="searchQuery"
        size="small"
        :placeholder="
          $t('ai-platform.workflow.editor.variableSelector.searchPlaceholder')
        "
        :prefix-icon="Search"
      />
    </div>
    <ElScrollbar class="flex-1">
      <div
        v-if="filteredNodes.length === 0"
        class="text-muted-foreground p-4 text-center text-xs"
      >
        {{ $t('ai-platform.workflow.editor.variableSelector.noVariables') }}
      </div>
      <div v-else class="p-2">
        <div v-for="node in filteredNodes" :key="node.id" class="mb-1">
          <div
            class="bg-muted/50 text-foreground hover:bg-muted flex cursor-pointer items-center gap-2 rounded px-2 py-1 text-xs font-medium transition-colors"
            @click="toggleNodeCollapse(node.id)"
          >
            <component
              :is="isNodeCollapsed(node.id) ? ChevronRight : ChevronDown"
              class="text-muted-foreground size-3 shrink-0"
            />
            <component
              :is="icons[node.type]"
              class="text-muted-foreground size-3 shrink-0"
            />
            <span class="flex-1 truncate">{{ node.label }}</span>
            <span class="text-muted-foreground text-[10px]">{{
              node.variables.length
            }}</span>
          </div>
          <div v-if="!isNodeCollapsed(node.id)" class="mt-1 space-y-0.5">
            <ElTooltip
              v-for="v in node.variables"
              :key="v.key"
              :content="v.label"
              placement="left"
              :show-after="500"
            >
              <div
                class="hover:bg-accent hover:text-primary flex cursor-pointer flex-col rounded px-2 py-1.5 text-xs transition-colors"
                :class="{
                  'bg-primary/5 text-primary': v.isSystem,
                  'bg-green-500/5 text-green-600 dark:text-green-400':
                    v.isField,
                  'bg-blue-500/5 text-blue-600 dark:text-blue-400':
                    v.isStructured,
                  'text-muted-foreground':
                    !v.isSystem && !v.isField && !v.isStructured,
                }"
                @click="handleSelect(node.id, v.key)"
              >
                <div class="flex items-center gap-1">
                  <span class="font-mono text-[10px]">{{ v.key }}</span>
                  <span
                    v-if="v.isSystem"
                    class="bg-primary/20 text-primary rounded px-1 text-[9px]"
                    >{{
                      $t('ai-platform.workflow.editor.variableSelector.system')
                    }}</span
                  >
                  <span
                    v-if="v.isField"
                    class="rounded bg-green-500/20 px-1 text-[9px] text-green-600 dark:text-green-400"
                    >{{
                      $t('ai-platform.workflow.editor.variableSelector.field')
                    }}</span
                  >
                  <span
                    v-if="v.isStructured"
                    class="rounded bg-blue-500/20 px-1 text-[9px] text-blue-600 dark:text-blue-400"
                    >{{
                      $t(
                        'ai-platform.workflow.editor.variableSelector.structured',
                      )
                    }}</span
                  >
                </div>
                <span
                  class="text-muted-foreground mt-0.5 truncate text-[10px]"
                  >{{ v.label }}</span>
              </div>
            </ElTooltip>
          </div>
        </div>
      </div>
    </ElScrollbar>
  </div>
</template>
