import React, { useState, useEffect, forwardRef } from 'react';
import '@wangeditor/editor/dist/css/style.css';
import { Editor, Toolbar } from '@wangeditor/editor-for-react';
import {
  IDomEditor,
  IEditorConfig,
  IToolbarConfig,
  i18nChangeLanguage,
  i18nAddResources,
} from '@wangeditor/editor';

// 定义多语言组件属性
export interface WangEditorProps {
  value?: string;
  onChange?: (html: string) => void;
  language?: 'zh-CN' | 'en';
  height?: string;
  placeholder?: string;
  mode?: 'default' | 'simple';
  readOnly?: boolean;
  toolbarKeys?: string[];
}

// 添加全局多语言配置
i18nAddResources('zh-CN', {
  editor: {
    placeholder: '请输入内容...',
  },
});

i18nAddResources('en', {
  editor: {
    placeholder: 'Please enter content...',
  },
});

// 使用forwardRef以便能在Form.Item中使用ref
const WangEditor = forwardRef<any, WangEditorProps>(({
  value = '',
  onChange,
  language = 'zh-CN',
  height = '300px',
  placeholder,
  mode = 'default',
  readOnly = false,
  toolbarKeys,
}, ref) => {
  // 编辑器实例
  const [editor, setEditor] = useState<IDomEditor | null>(null);
  // HTML内容
  const [html, setHtml] = useState<string>(value);

  // 设置语言
  useEffect(() => {
    i18nChangeLanguage(language);
  }, [language]);

  // 工具栏配置
  const toolbarConfig: Partial<IToolbarConfig> = {
    excludeKeys: [],
  };

  if (toolbarKeys) {
    toolbarConfig.toolbarKeys = toolbarKeys;
  }

  // 编辑器配置
  const editorConfig: Partial<IEditorConfig> = {
    placeholder: placeholder || (language === 'zh-CN' ? '请输入内容...' : 'Please enter content...'),
    readOnly,
  };

  // 监听value变化
  useEffect(() => {
    if (editor && value !== html) {
      setHtml(value);
    }
  }, [value, editor]);

  // 及时销毁editor实例，重要！
  useEffect(() => {
    return () => {
      if (editor == null) return;
      editor.destroy();
      setEditor(null);
    };
  }, [editor]);

  // 处理编辑器内容变化
  const handleChange = (newEditor: IDomEditor) => {
    const newHtml = newEditor.getHtml();
    setHtml(newHtml);

    // 调用Form.Item的onChange回调，支持表单验证
    if (onChange) {
      // 如果内容为空或只有空段落，传递空字符串以触发验证
      if (!newHtml || newHtml === '<p></p>' || newHtml === '<p><br></p>') {
        onChange('');
      } else {
        onChange(newHtml);
      }
    }
  };

  return (
    <div style={{ width: '100%' }}>
      <div style={{ border: '1px solid #ccc', zIndex: 100 }}>
        {!readOnly && (
          <Toolbar
            editor={editor}
            defaultConfig={toolbarConfig}
            mode={mode}
            style={{ borderBottom: '1px solid #ccc' }}
          />
        )}
        <Editor
          defaultConfig={editorConfig}
          value={html}
          onCreated={setEditor}
          onChange={handleChange}
          mode={mode}
          style={{ height, overflowY: 'hidden' }}
        />
      </div>
    </div>
  );
});

export default WangEditor;
