/**
 * 快捷回复 Tiptap 扩展（PC 端）
 * - 触发字符：#
 * - 选中项：
 *   - text 类型：删除 range，插入纯文本
 *   - image / video 类型：删除 range，通过 editor.emit('insertImage' | 'insertVideo') 通知外层处理
 */
import { Extension, type Range } from '@tiptap/vue-3';
import { PluginKey } from '@tiptap/pm/state';
import SuggestionExtension from '@tiptap/suggestion';

export const quickReplySuggestionPluginKey = new PluginKey('quickReplySuggestion');

export const QuickReplyExtension = Extension.create({
    name: 'quickReply',

    addOptions() {
        return {
            suggestion: {
                char: '#',
                allowedPrefixes: null,
                allowSpaces: true,
                command: ({
                    editor,
                    range,
                    props,
                }: {
                    // eslint-disable-next-line @typescript-eslint/no-explicit-any
                    editor: any;
                    range: Range;
                    props: { id: string; content: string; format: string; thumbImage: string };
                }) => {
                    if (props.format === 'text' || props.format === '') {
                        editor
                            .chain()
                            .focus()
                            .deleteRange(range)
                            .insertContent(props.content)
                            .run();
                        return;
                    }
                    if (props.format === 'image') {
                        editor.chain().focus().deleteRange(range).run();
                        editor.emit('insertImage', {
                            src: props.content,
                            type: 'image',
                            thumbImage: props.thumbImage,
                        });
                        return;
                    }
                    if (props.format === 'video') {
                        editor.chain().focus().deleteRange(range).run();
                        editor.emit('insertVideo', {
                            src: props.content,
                            type: 'video',
                            thumbImage: props.thumbImage,
                        });
                    }
                },
            },
        };
    },

    addProseMirrorPlugins() {
        return [
            SuggestionExtension({
                editor: this.editor,
                pluginKey: quickReplySuggestionPluginKey,
                ...this.options.suggestion,
            }),
        ];
    },
});

export default QuickReplyExtension;
