/**
 * 模板编辑器组件
 * 基于 Monaco Editor 实现，支持 FreeMarker 语法
 */
import React, { useEffect, useRef, useState } from 'react';
import { Button } from '@/components/ui/button';
import { ScrollArea } from '@/components/ui/scroll-area';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogBody,
  DialogFooter,
} from '@/components/ui/dialog';
import { Settings } from 'lucide-react';
import { FormDesigner, FormRenderer, type FormSchema } from '@/components/FormDesigner';
import Editor from '@/components/Editor';
import { NotificationChannelType } from '../../../NotificationChannel/List/types';
import type { editor } from 'monaco-editor';

// 模板变量类型（可选）
export interface TemplateVariable {
  name: string;
  description?: string;
  type?: string;
  required?: boolean;
}

interface TemplateEditorProps {
  value: string;
  onChange: (value: string) => void;
  channelType: NotificationChannelType;
  variables?: TemplateVariable[]; // 可选
  onVariableInsert?: (variable: TemplateVariable) => void; // 可选
  onFormDataChange?: (data: Record<string, any>) => void; // 表单数据变化回调
  mode?: 'create' | 'edit'; // 模式标识
}

export const TemplateEditor: React.FC<TemplateEditorProps> = ({
  value,
  onChange,
  channelType,
  variables = [],
  onVariableInsert,
  onFormDataChange,
  mode = 'edit',
}) => {
  const editorRef = useRef<editor.IStandaloneCodeEditor | null>(null);
  const [designerDialogOpen, setDesignerDialogOpen] = useState(false);
  const [formSchema, setFormSchema] = useState<FormSchema | null>(null);
  const [formData, setFormData] = useState<Record<string, any>>({});

  // 当表单数据变化时，通知父组件
  useEffect(() => {
    if (onFormDataChange) {
      onFormDataChange(formData);
    }
  }, [formData, onFormDataChange]);

  // 注册 FreeMarker 语言支持
  useEffect(() => {
    const registerFreeMarker = async () => {
      const monaco = await import('monaco-editor');
      
      // 注册 FreeMarker 语言
      if (!monaco.languages.getLanguages().find(lang => lang.id === 'freemarker')) {
        monaco.languages.register({ id: 'freemarker' });
        
        // 设置 FreeMarker 语法高亮
        monaco.languages.setMonarchTokensProvider('freemarker', {
          keywords: [
            'if', 'else', 'elseif', 'endif',
            'list', 'endlist', 'items',
            'macro', 'endmacro', 'return',
            'function', 'endfunction',
            'assign', 'local', 'global',
            'include', 'import', 'nested',
            'compress', 'endcompress',
            'escape', 'noescape', 'endescape',
            'attempt', 'recover', 'endattempt',
            'switch', 'case', 'default', 'endswitch',
            'visit', 'recurse', 'fallback',
            'setting', 'flush', 'stop',
            'lt', 'lte', 'gt', 'gte'
          ],
          
          operators: [
            '=', '>', '<', '!', '~', '?', ':',
            '==', '<=', '>=', '!=', '&&', '||', '++', '--',
            '+', '-', '*', '/', '&', '|', '^', '%', '<<',
            '>>', '>>>', '+=', '-=', '*=', '/=', '&=', '|=',
            '^=', '%=', '<<=', '>>=', '>>>='
          ],
          
          symbols: /[=><!~?:&|+\-*\/\^%]+/,
          
          tokenizer: {
            root: [
              // FreeMarker 指令
              [/<#[a-zA-Z_][a-zA-Z0-9_]*/, 'keyword'],
              [/<\/#[a-zA-Z_][a-zA-Z0-9_]*>/, 'keyword'],
              [/<#--/, 'comment', '@comment'],
              
              // FreeMarker 表达式
              [/\$\{/, 'delimiter', '@expression'],
              
              // 字符串
              [/"([^"\\]|\\.)*$/, 'string.invalid'],
              [/"/, 'string', '@string'],
              [/'([^'\\]|\\.)*$/, 'string.invalid'],
              [/'/, 'string', '@string_single'],
              
              // 数字
              [/\d*\.\d+([eE][\-+]?\d+)?/, 'number.float'],
              [/\d+/, 'number'],
              
              // 标识符和关键字
              [/[a-zA-Z_$][\w$]*/, {
                cases: {
                  '@keywords': 'keyword',
                  '@default': 'identifier'
                }
              }],
              
              // 操作符
              [/@symbols/, {
                cases: {
                  '@operators': 'operator',
                  '@default': ''
                }
              }],
              
              // 空白字符
              [/[ \t\r\n]+/, 'white'],
            ],
            
            comment: [
              [/[^<-]+/, 'comment'],
              [/-->/, 'comment', '@pop'],
              [/[<-]/, 'comment']
            ],
            
            expression: [
              [/[^}]+/, 'variable'],
              [/}/, 'delimiter', '@pop']
            ],
            
            string: [
              [/[^\\"]+/, 'string'],
              [/\\./, 'string.escape'],
              [/"/, 'string', '@pop']
            ],
            
            string_single: [
              [/[^\\']+/, 'string'],
              [/\\./, 'string.escape'],
              [/'/, 'string', '@pop']
            ]
          }
        });
        
        // 设置自动完成
        monaco.languages.registerCompletionItemProvider('freemarker', {
          // 使用宽松的类型以兼容不同版本的 monaco 类型定义
          provideCompletionItems: (
            model: any,
            position: any,
            context?: any,
            token?: any
          ) => {
            const suggestions = [
              // FreeMarker 指令
              ...['if', 'list', 'assign', 'include', 'macro'].map(keyword => ({
                label: `<#${keyword}>`,
                kind: monaco.languages.CompletionItemKind.Keyword,
                insertText: `<#${keyword} >\n</#${keyword}>`,
                insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
                documentation: `FreeMarker ${keyword} directive`
              })),
              
              // 变量建议
              ...(variables || []).map(variable => ({
                label: `\${${variable.name}}`,
                kind: monaco.languages.CompletionItemKind.Variable,
                insertText: `\${${variable.name}}`,
                documentation: variable.description,
                detail: `${variable.type ?? ''} ${variable.required ? '- Required' : ''}`
              }))
            ];
            
            return { suggestions } as any; // 兼容 CompletionList 类型
          }
        });
      }
    };
    
    registerFreeMarker();
  }, [variables]);

  const handleEditorDidMount = (
    ed: editor.IStandaloneCodeEditor,
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    monacoInstance?: unknown
  ) => {
    editorRef.current = ed;
  };

  const getVariableTypeColor = (type: string) => {
    switch (type) {
      case 'string': return 'bg-blue-100 text-blue-800';
      case 'number': return 'bg-green-100 text-green-800';
      case 'boolean': return 'bg-purple-100 text-purple-800';
      case 'object': return 'bg-orange-100 text-orange-800';
      case 'array': return 'bg-pink-100 text-pink-800';
      default: return 'bg-gray-100 text-gray-800';
    }
  };

  return (
    <div className="flex gap-4 h-full w-full">
      {/* 编辑器区域 */}
      <div className="flex-1 border rounded-lg flex flex-col overflow-hidden">
        <div className="p-3 border-b bg-muted/50 flex-shrink-0">
          <h3 className="font-medium">模板编辑器</h3>
          <p className="text-xs text-muted-foreground mt-1">
            支持 FreeMarker 语法，使用 ${'{'}变量名{'}'} 插入变量
          </p>
        </div>
        
        <div className="flex-1 overflow-hidden">
          <Editor
            value={value}
            onChange={onChange}
            language="freemarker"
            theme="vs-light"
            onMount={handleEditorDidMount as any}
            options={{
              minimap: { enabled: false },
              scrollBeyondLastLine: false,
              wordWrap: 'on',
              lineNumbers: 'on',
              glyphMargin: false,
              folding: false,
              lineDecorationsWidth: 10, // 增加行装饰宽度
              lineNumbersMinChars: 4, // 增加行号最小字符数
              fontSize: 14,
              fontFamily: 'Monaco, Menlo, "Ubuntu Mono", monospace',
              automaticLayout: true,
              contextmenu: true,
              selectOnLineNumbers: true,
              roundedSelection: false,
              readOnly: false,
              cursorStyle: 'line',
              accessibilitySupport: 'auto',
              quickSuggestions: true,
              suggestOnTriggerCharacters: true,
              acceptSuggestionOnEnter: 'on',
              tabCompletion: 'on',
              // 滚动条设置
              scrollbar: {
                vertical: 'visible',
                horizontal: 'visible',
                verticalScrollbarSize: 14,
                horizontalScrollbarSize: 14,
                verticalSliderSize: 14,
                horizontalSliderSize: 14,
              },
              // 行号和内容的间距
              padding: {
                top: 10,
                bottom: 10,
              },
              // 行高设置，增加行间距
              lineHeight: 1.6,
              // 启用滚动
              overviewRulerLanes: 0,
              hideCursorInOverviewRuler: true,
            }}
          />
        </div>
      </div>

      {/* 变量面板 - 只在编辑模式显示 */}
      {mode === 'edit' && (
      <div className="w-80 border rounded-lg flex flex-col overflow-hidden">
        <div className="p-3 border-b bg-muted/50 flex-shrink-0">
          <div className="flex items-center justify-between">
            <div>
              <h3 className="font-medium">可用变量</h3>
              <p className="text-xs text-muted-foreground mt-1">
                {formSchema ? '使用表单设计器管理的变量' : '点击设计器按钮创建变量表单'}
              </p>
            </div>
            <Button
              type="button"
              variant="ghost"
              size="sm"
              onClick={() => setDesignerDialogOpen(true)}
              title="打开表单设计器"
            >
              <Settings className="h-4 w-4" />
            </Button>
          </div>
        </div>
        
        <div className="flex-1 overflow-hidden">
          {formSchema ? (
            <ScrollArea className="h-full">
              <div className="p-3">
              <FormRenderer
                schema={formSchema}
                onChange={(data) => {
                  setFormData(data);
                }}
                showSubmit={false}
                  showCancel={false}
                />
              </div>
            </ScrollArea>
          ) : (
            <div className="flex items-center justify-center h-full p-8">
              <div className="text-center text-muted-foreground">
                <Settings className="h-12 w-12 mx-auto mb-3 opacity-30" />
                <p className="text-sm mb-2">暂无变量表单</p>
                <p className="text-xs">点击设计器按钮创建</p>
              </div>
            </div>
          )}
        </div>
      </div>
      )}

      {/* FormDesigner对话框 */}
      <Dialog open={designerDialogOpen} onOpenChange={setDesignerDialogOpen}>
        <DialogContent className="max-w-6xl max-h-[90vh] overflow-hidden">
          <DialogHeader>
            <DialogTitle>表单设计器</DialogTitle>
          </DialogHeader>
          <DialogBody className="flex-1 overflow-hidden">
            <div className="h-[70vh]">
              <FormDesigner
                value={formSchema}
                onChange={setFormSchema}
                onSave={(schema) => {
                  setFormSchema(schema);
                  setDesignerDialogOpen(false);
                }}
              />
            </div>
          </DialogBody>
          <DialogFooter>
            <Button variant="outline" onClick={() => setDesignerDialogOpen(false)}>
              取消
            </Button>
            <Button onClick={() => setDesignerDialogOpen(false)}>
              完成
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
};
