import { myModalMenuConf } from '@/components/Editor/ModalMenu';
import { ProFormField, ProFormFieldProps } from '@ant-design/pro-components';
import {
	Boot,
	IDomEditor,
	IEditorConfig,
	IToolbarConfig,
} from '@wangeditor-next/editor';
import { Editor, Toolbar } from '@wangeditor-next/editor-for-react';
import '@wangeditor-next/editor/dist/css/style.css';
import { useEffect, useState } from 'react';

// @ts-ignore
Boot.registerMenu(myModalMenuConf);

export interface BizEditorProps extends ProFormFieldProps {
	value?: string;
	intlPrefix?: string;
	onChange?: (value: string) => void;
}

function MyEditor(props: BizEditorProps) {
	const { value, onChange } = props;
	// editor 实例
	const [editor, setEditor] = useState<IDomEditor | null>(null); // TS 语法

	// 工具栏配置
	const toolbarConfig: Partial<IToolbarConfig> = {
		insertKeys: {
			index: 0, // 插入的位置，基于当前的 toolbarKeys
			keys: ['materialMenu'],
		},
	}; // TS 语法

	// 编辑器配置
	const editorConfig: Partial<IEditorConfig> = {
		// TS 语法
		placeholder: '请输入内容...',
	};

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

	return (
		<div style={{ border: '1px solid #ccc', zIndex: 100 }}>
			<Toolbar
				editor={editor}
				defaultConfig={toolbarConfig}
				mode="default"
				style={{ borderBottom: '1px solid #ccc' }}
			/>
			<Editor
				defaultConfig={editorConfig}
				value={value}
				onCreated={(editor) => {
					setEditor(editor);
				}}
				onChange={(editor) => {
					onChange?.(editor.getHtml());
				}}
				mode="default"
				style={{ height: '500px', overflowY: 'hidden' }}
			/>
		</div>
	);
}

export default function BizEditor(props: BizEditorProps) {
	const { value, onChange, ...rest } = props;

	return (
		<ProFormField {...rest}>
			<MyEditor value={value} onChange={onChange} />
		</ProFormField>
	);
}
