import React, { useState, useEffect } from 'react';
import { Editor, Toolbar } from '@wangeditor/editor-for-react';
import { IDomEditor, IEditorConfig, IToolbarConfig } from '@wangeditor/editor';
import styles from './index.module.css';

interface RichTextEditorProps {
    value?: string;
    onChange?: (html: string) => void;
    placeholder?: string;
}

const RichTextEditor: React.FC<RichTextEditorProps> = ({
    value = '',
    onChange,
    placeholder = '请输入内容...'
}) => {
    // 存储 editor 实例
    const [editor, setEditor] = useState<IDomEditor | null>(null);

    // 编辑器配置
    const editorConfig: Partial<IEditorConfig> = {
        placeholder,
        MENU_CONF: {
            uploadImage: {
                // 这里可以配置实际的上传接口，目前先使用 base64
                base64LimitSize: 5 * 1024 * 1024, // 5M 以内使用 base64
            }
        }
    };

    // 工具栏配置
    const toolbarConfig: Partial<IToolbarConfig> = {
        excludeKeys: [
            'fullScreen', // 排除全屏，因为在 Modal 中全屏会有布局问题
        ]
    };

    // 及时销毁编辑器
    useEffect(() => {
        return () => {
            if (editor == null) return;
            editor.destroy();
            setEditor(null);
        };
    }, [editor]);

    return (
        <div className={styles.editorContainer}>
            <Toolbar
                editor={editor}
                defaultConfig={toolbarConfig}
                mode="default"
                className={styles.toolbar}
            />
            <Editor
                defaultConfig={editorConfig}
                value={value}
                onCreated={setEditor}
                onChange={(editor) => {
                    const html = editor.getHtml();
                    if (onChange) {
                        onChange(html);
                    }
                }}
                mode="default"
                className={styles.editor}
            />
        </div>
    );
};

export default RichTextEditor;
