/**
 * 快捷回复 Suggestion 配置（PC 端）
 * - 使用 tippy.js 弹层
 * - 使用 @tiptap/vue-3 的 VueRenderer 挂载 QuickReplyList.vue
 */
/* eslint-disable @typescript-eslint/no-explicit-any */
import { VueRenderer } from '@tiptap/vue-3';
import tippy, { type Instance as TippyInstance } from 'tippy.js';
import AIDeskCoreInstance from '@tencentcloud/ai-desk-core';
import QuickReplyList from './QuickReplyList.vue';

type QuickReplyItem = {
    quickReplyId: string;
    groupId: string;
    title: string;
    content: string;
    format?: string;
    thumbImage?: string;
};

type QuickReplyGroup = {
    groupId: string;
    groupName: string;
    quickReplyList: QuickReplyItem[] | null;
};

type FormattedReplyItem = {
    id: string;
    content: string;
    title: string;
    group: string;
    groupId: string;
    format: string;
    thumbImage: string;
};

const fetchQuickReplyList = async (): Promise<FormattedReplyItem[]> => {
    try {
        const groups = (await AIDeskCoreInstance.chatService.getAllAvailableQuickReply()) as
            | QuickReplyGroup[]
            | undefined;
        if (!Array.isArray(groups)) return [];
        const result: FormattedReplyItem[] = [];
        groups.forEach((groupItem) => {
            (groupItem.quickReplyList || []).forEach((item) => {
                result.push({
                    id: item.quickReplyId,
                    content: item.content,
                    title: item.title,
                    group: groupItem.groupName,
                    groupId: item.groupId,
                    format: item.format ?? '',
                    thumbImage: item.thumbImage ?? '',
                });
            });
        });
        return result;
    } catch (error) {
        console.error('[QuickReply] getAllAvailableQuickReply error', error);
        return [];
    }
};

const suggestionConfig = () => ({
    items: async ({ query }: { query: string }) => {
        const list = await fetchQuickReplyList();
        if (!query) return list;
        const keyword = query.toLowerCase();
        return list.filter(
            (item) =>
                item.content.toLowerCase().includes(keyword) ||
                item.title.toLowerCase().includes(keyword),
        );
    },

    render: () => {
        let component: VueRenderer | undefined;
        let popup: TippyInstance[] | undefined;

        return {
            onStart: (props: any) => {
                component = new VueRenderer(QuickReplyList, {
                    props,
                    editor: props.editor,
                });

                if (!props.clientRect || !component.element) return;

                popup = tippy('body', {
                    getReferenceClientRect: props.clientRect,
                    appendTo: () => document.body,
                    content: component.element as Element,
                    showOnCreate: true,
                    interactive: true,
                    trigger: 'manual',
                    placement: 'top-start',
                    maxWidth: 640,
                    zIndex: 9999,
                    arrow: false,
                    theme: 'qr-suggest',
                });
            },

            onUpdate(props: any) {
                component?.updateProps(props);
                if (!props.clientRect) return;
                if (!popup && component?.element) {
                    popup = tippy('body', {
                        getReferenceClientRect: props.clientRect,
                        appendTo: () => document.body,
                        content: component.element as Element,
                        showOnCreate: true,
                        interactive: true,
                        trigger: 'manual',
                        placement: 'top-start',
                        maxWidth: 640,
                        zIndex: 9999,
                        arrow: false,
                        theme: 'qr-suggest',
                    });
                }
                popup?.[0]?.setProps({ getReferenceClientRect: props.clientRect });
            },

            onKeyDown(props: any) {
                if (props.event.key === 'Escape') {
                    popup?.[0]?.destroy();
                    component?.destroy();
                    popup = undefined;
                    component = undefined;
                    return true;
                }
                // 转发键盘事件给列表组件
                return (component?.ref as any)?.onKeyDown?.(props) ?? false;
            },

            onExit() {
                popup?.[0]?.destroy();
                component?.destroy();
                popup = undefined;
                component = undefined;
            },
        };
    },
});

export default suggestionConfig;
