import React, { useEffect, useRef } from 'react';
import { EditorView, keymap, placeholder as placeholderExtension, Decoration, DecorationSet, ViewPlugin, ViewUpdate } from '@codemirror/view';
import { EditorState, Compartment, Range } from '@codemirror/state';
import { autocompletion, CompletionContext } from '@codemirror/autocomplete';
import { defaultKeymap, history, historyKeymap } from '@codemirror/commands';
import { bracketMatching, indentOnInput, syntaxHighlighting, defaultHighlightStyle } from '@codemirror/language';
import { oneDark } from '@codemirror/theme-one-dark';
import { javascript } from '@codemirror/lang-javascript';
import type { FlowNode, FlowEdge } from '@/pages/Workflow/Design/types';
import type { FormField } from './types';
import { collectNodeVariables } from '@/utils/workflow/collectNodeVariables';

// 🎨 变量高亮装饰器（简洁方案：整体高亮）
const variableMark = Decoration.mark({ 
  class: 'cm-variable-highlight'
});

// 🔍 匹配 ${...} 变量的正则表达式
const variableRegex = /\$\{[^}]*\}/g;

// 🎨 变量高亮插件
const variableHighlighter = ViewPlugin.fromClass(class {
  decorations: DecorationSet;

  constructor(view: EditorView) {
    this.decorations = this.buildDecorations(view);
  }

  update(update: ViewUpdate) {
    if (update.docChanged || update.viewportChanged) {
      this.decorations = this.buildDecorations(update.view);
    }
  }

  buildDecorations(view: EditorView): DecorationSet {
    const decorations: Range<Decoration>[] = [];
    const text = view.state.doc.toString();
    let match: RegExpExecArray | null;

    // 重置正则的 lastIndex
    variableRegex.lastIndex = 0;

    while ((match = variableRegex.exec(text)) !== null) {
      const start = match.index;
      const end = start + match[0].length;

      // 整体高亮（避免空范围错误）
      if (end > start) {
        decorations.push(variableMark.range(start, end));
      }
    }

    return Decoration.set(decorations);
  }
}, {
  decorations: v => v.decorations
});

export interface CodeMirrorVariableInputProps {
    // 基本属性
    value: string | number | undefined;
    onChange: (value: string | number | undefined) => void;
    placeholder?: string;
    disabled?: boolean;
    
    // 变量配置
    allNodes: FlowNode[];
    allEdges: FlowEdge[];
    currentNodeId: string;
    formFields?: FormField[];
    
    // 样式配置
    variant?: 'input' | 'textarea';
    rows?: number;
    theme?: 'light' | 'dark';
    
    // 高级配置
    /** 是否自动转换数字类型（默认 false）*/
    autoConvertNumber?: boolean;
    /** 当用户正在编辑时的回调 */
    onEditingChange?: (isEditing: boolean) => void;
}

/**
 * CodeMirror 变量输入组件
 * 使用 CodeMirror 6 实现变量自动补全和语法高亮
 * 
 * 内部功能：
 * - 自动处理空值转换（'' -> undefined）
 * - 可选的数字类型自动转换
 * - 变量表达式检测（包含 ${} 时保持字符串类型）
 * - 编辑状态追踪
 */
export const CodeMirrorVariableInput: React.FC<CodeMirrorVariableInputProps> = ({
    value,
    onChange,
    placeholder = '',
    disabled = false,
    allNodes,
    allEdges,
    currentNodeId,
    formFields = [],
    variant = 'input',
    rows = 3,
    theme = 'light',
    autoConvertNumber = false,
    onEditingChange
}) => {
    const editorRef = useRef<HTMLDivElement>(null);
    const viewRef = useRef<EditorView | null>(null);
    const onChangeRef = useRef(onChange);
    const onEditingChangeRef = useRef(onEditingChange);
    const editingTimeoutRef = useRef<number | null>(null);
    
    // ✅ 添加用户编辑状态标记（防止编辑时被外部 value 覆盖）
    const isUserEditingRef = useRef(false);
    
    // 同步 onChange 和 onEditingChange 引用
    useEffect(() => {
        onChangeRef.current = onChange;
        onEditingChangeRef.current = onEditingChange;
    }, [onChange, onEditingChange]);
    
    // 智能值转换处理
    const handleValueChange = (newValue: string) => {
        // ✅ 标记用户正在编辑
        isUserEditingRef.current = true;
        
        // 通知外部：用户开始编辑
        onEditingChangeRef.current?.(true);
        
        // 清除之前的定时器
        if (editingTimeoutRef.current) {
            clearTimeout(editingTimeoutRef.current);
        }
        
        // 300ms 后通知编辑结束并重置编辑状态
        editingTimeoutRef.current = window.setTimeout(() => {
            onEditingChangeRef.current?.(false);
            isUserEditingRef.current = false; // ✅ 重置编辑状态
        }, 300);
        
        // 值转换逻辑
        if (newValue === '') {
            // 空值转换为 undefined
            onChangeRef.current(undefined);
        } else if (newValue.includes('${')) {
            // 包含变量语法，保持字符串类型
            onChangeRef.current(newValue);
        } else if (autoConvertNumber) {
            // 自动转换数字（如果启用）
            const numValue = Number(newValue);
            onChangeRef.current(isNaN(numValue) ? newValue : numValue);
        } else {
            // 普通字符串
            onChangeRef.current(newValue);
        }
    };
    
    // 收集所有可用变量
    const allVariables = React.useMemo(() => {
        // 表单字段变量（去除 form. 前缀，直接使用原始字段名）
        const formVariables = formFields.map(field => ({
            nodeId: 'form',
            nodeName: '启动表单',
            fieldName: field.name,
            fieldType: field.type,
            fieldDescription: field.label, // ✅ 使用表单字段的 label 作为描述
            displayText: `\${${field.name}}`,
            fullText: `${field.name}`,
        }));
        
        // 节点变量
        const nodeVariables = collectNodeVariables(currentNodeId, allNodes, allEdges);
        
        return [...formVariables, ...nodeVariables];
    }, [formFields, currentNodeId, allNodes, allEdges]);
    
    // 使用 ref 存储变量，避免重新创建编辑器
    const allVariablesRef = useRef(allVariables);
    
    useEffect(() => {
        allVariablesRef.current = allVariables;
    }, [allVariables]);
    
    // 变量自动补全函数
    const variableCompletion = React.useCallback((context: CompletionContext) => {
        const word = context.matchBefore(/\$\{[^}]*/);
        
        if (!word) return null;
        
        // 如果不是以 ${ 开头，不显示补全
        if (!word.text.startsWith('${')) return null;
        
        // 提取搜索文本（去掉 ${）
        const searchText = word.text.slice(2).toLowerCase();
        
        // 过滤变量（使用 ref 中的最新值）
        const filteredVariables = allVariablesRef.current.filter(v => 
            v.fullText.toLowerCase().includes(searchText) ||
            v.nodeName.toLowerCase().includes(searchText) ||
            v.fieldName.toLowerCase().includes(searchText)
        );
        
        return {
            from: word.from,
            options: filteredVariables.map(v => ({
                label: v.displayText,
                type: 'variable',
                // ✅ 优先显示字段描述，若无描述则显示"节点名 - 字段名"
                info: v.fieldDescription || `${v.nodeName} - ${v.fieldName}`,
                apply: v.displayText,
            })),
        };
    }, []);
    
    // 初始化 CodeMirror
    useEffect(() => {
        if (!editorRef.current) return;
        
        // 创建主题 Compartment（允许动态切换）
        const themeCompartment = new Compartment();
        
        // 基础扩展（替代 basicSetup）
        const basicExtensions = [
            history(),
            indentOnInput(),
            bracketMatching(),
            // ❌ 移除 closeBrackets() - 避免输入 ${ 时自动补全 }
            // ❌ 移除 closeBracketsKeymap - 避免自动关闭括号
            syntaxHighlighting(defaultHighlightStyle),
            keymap.of([
                ...defaultKeymap,
                ...historyKeymap,
            ]),
        ];
        
        // 创建 EditorState
        const state = EditorState.create({
            doc: String(value || ''),
            extensions: [
                ...basicExtensions,
                // 🎨 变量高亮插件（必须在主题之前）
                variableHighlighter,
                // 根据 variant 设置高度
                EditorView.theme({
                    '&': {
                        height: variant === 'input' ? '38px' : `${rows * 24}px`,
                        fontSize: '14px',
                        border: '1px solid hsl(var(--border))',
                        borderRadius: 'calc(var(--radius) - 2px)',
                    },
                    '&.cm-focused': {
                        outline: '2px solid hsl(var(--ring))',
                        outlineOffset: '2px',
                    },
                    '.cm-scroller': {
                        overflow: variant === 'input' ? 'hidden' : 'auto',
                        fontFamily: 'inherit',
                    },
                    '.cm-content': {
                        padding: variant === 'input' ? '8px 12px' : '12px',
                        caretColor: 'hsl(var(--foreground))',
                    },
                    '.cm-line': {
                        padding: 0,
                    },
                    '&.cm-editor.cm-focused': {
                        outline: 'none',
                    },
                    '.cm-placeholder': {
                        color: 'hsl(var(--muted-foreground))',
                    },
                    // 🎨 变量高亮样式（简洁方案）
                    '.cm-variable-highlight': {
                        color: '#2563eb', // 蓝色高亮
                        fontWeight: '600',
                        backgroundColor: '#dbeafe', // 浅蓝色背景
                        padding: '1px 2px',
                        borderRadius: '2px',
                    }
                }),
                // 主题
                themeCompartment.of(theme === 'dark' ? oneDark : []),
                // JavaScript 语法高亮（用于高亮变量语法）
                javascript(),
                // 自动补全
                autocompletion({
                    override: [variableCompletion],
                    closeOnBlur: false,
                }),
                // placeholder
                placeholder ? placeholderExtension(placeholder) : [],
                // 值变化监听
                EditorView.updateListener.of((update) => {
                    if (update.docChanged) {
                        const newValue = update.state.doc.toString();
                        handleValueChange(newValue);
                    }
                }),
                // 禁用状态
                EditorView.editable.of(!disabled),
                EditorState.readOnly.of(disabled),
                // 单行输入模式
                ...(variant === 'input' ? [
                    EditorState.transactionFilter.of((tr) => {
                        // 阻止换行
                        if (tr.newDoc.lines > 1) {
                            return [];
                        }
                        return tr;
                    })
                ] : []),
            ],
        });
        
        // 创建 EditorView
        const view = new EditorView({
            state,
            parent: editorRef.current,
        });
        
        viewRef.current = view;
        
        // 清理函数
        return () => {
            view.destroy();
            viewRef.current = null;
        };
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [variant, rows, theme, disabled, placeholder, variableCompletion]);
    
    // 当外部 value 变化时，更新编辑器内容
    // ✅ 添加保护：用户正在编辑时，不同步外部 value（防止删除时恢复）
    useEffect(() => {
        if (!viewRef.current) return;
        
        // ⚠️ 如果用户正在编辑，跳过同步（防止删除操作被覆盖）
        if (isUserEditingRef.current) {
            return;
        }
        
        const stringValue = String(value || '');
        const currentValue = viewRef.current.state.doc.toString();
        if (currentValue !== stringValue) {
            viewRef.current.dispatch({
                changes: {
                    from: 0,
                    to: currentValue.length,
                    insert: stringValue,
                },
            });
        }
    }, [value]);
    
    return (
        <div
            ref={editorRef}
            className="codemirror-variable-input"
            style={{
                opacity: disabled ? 0.5 : 1,
                pointerEvents: disabled ? 'none' : 'auto',
            }}
        />
    );
};

export default CodeMirrorVariableInput;

