import { defineComponent, computed, onMounted, onUnmounted, ref, nextTick } from "vue";
import { useBackendStore, useMainWindowStore } from "@/stores";
import { MAIN_WINDOW_WORKSPACE_PAGES } from "@/types/mainwindow";
import SvgIcon from "@/components/SvgIcon";

/**
 * 底部信息栏组件
 */
export default defineComponent({
    name: "Footer",
    components: {
        SvgIcon,
    },

    props: {
        isPanelFullscreen: {
            type: Boolean,
            default: false,
        },
    },

    setup(props) {
        const backendStore = useBackendStore();
        const mainWindowStore = useMainWindowStore();
        const shortcutList = ref<string[]>([]);
        const footerLeftRef = ref<HTMLElement | null>(null);
        const footerRightRef = ref<HTMLElement | null>(null);
        const footerRef = ref<HTMLElement | null>(null);
        const showRight = ref(true);

        const disclaimerText = computed(() =>
            backendStore.translate(
                "The content generated by AI is for reference only, please pay attention to the accuracy of the information.",
            ),
        );

        const quickOpenText = computed(() => backendStore.translate("Quick Open"));

        // 检测当前是否在聊天页面（有输入框的页面）
        const isChatPage = computed(() => {
            return mainWindowStore.workspacePage === MAIN_WINDOW_WORKSPACE_PAGES.CHAT && !props.isPanelFullscreen;
        });

        const checkOverflow = () => {
            if (footerRef.value && footerLeftRef.value && footerRightRef.value) {
                const leftWidth = footerLeftRef.value.scrollWidth;
                const rightWidth = footerRightRef.value.scrollWidth;
                const totalWidth = leftWidth + rightWidth + 40; // 40px for padding
                showRight.value = totalWidth <= footerRef.value.clientWidth;
            }
        };

        // ResizeObserver 实例
        let resizeObserver: ResizeObserver | null = null;

        onMounted(async () => {
            const shortcuts = await backendStore.requestSystem("getCurrentShortcut");
            console.log("current shortcuts:", shortcuts);
            // 解析快捷键字符串，如 "<Shift><Control><Alt><Super>A" 转换为 ["Shift", "Control", "Alt", "Super", "A"]
            if (shortcuts && typeof shortcuts === "string") {
                // 移除尖括号并分割成数组
                const keys = shortcuts.replace(/[<>]/g, " ").trim().split(/\s+/);
                shortcutList.value = keys.filter((key) => key.length > 0);

                // 将Control转换为Ctrl
                shortcutList.value = shortcutList.value.map((key) => (key === "Control" ? "Ctrl" : key));
            } else {
                shortcutList.value = [];
            }

            // 检测 footer__left 是否溢出
            nextTick(() => {
                checkOverflow();
            });

            // 使用 ResizeObserver 监听 Footer 容器尺寸变化
            if (footerRef.value && typeof ResizeObserver !== "undefined") {
                resizeObserver = new ResizeObserver(() => {
                    checkOverflow();
                });
                resizeObserver.observe(footerRef.value);
            }

            // 监听窗口大小变化
            window.addEventListener("resize", checkOverflow);
        });

        onUnmounted(() => {
            // 清理 ResizeObserver
            if (resizeObserver) {
                resizeObserver.disconnect();
                resizeObserver = null;
            }
            // 移除窗口大小监听
            window.removeEventListener("resize", checkOverflow);
        });

        return {
            disclaimerText,
            quickOpenText,
            shortcutList,
            footerLeftRef,
            footerRightRef,
            footerRef,
            showRight,
            isChatPage,
        };
    },

    render() {
        return (
            <div class={["footer", { "footer--with-input": this.isChatPage }]} ref="footerRef">
                <span class="footer__left" ref="footerLeftRef">
                    {this.disclaimerText}
                </span>
                {this.shortcutList.length > 0 && (
                    <div
                        class="footer__right"
                        ref="footerRightRef"
                        style={{ visibility: this.showRight ? "visible" : "hidden" }}
                    >
                        <div class="footer__shortcut">
                            {this.shortcutList.map((item, index) => (
                                <div class="footer__shortcut-item" key={item}>
                                    {item === "Super" ? (
                                        <div class="footer__super-icon">
                                            <SvgIcon icon="super" size={[8, 8]} />
                                        </div>
                                    ) : (
                                        <div class="footer__space-text">{item}</div>
                                    )}
                                    {index < this.shortcutList.length - 1 && <span class="footer__plus-sign">+</span>}
                                </div>
                            ))}
                            <span class="footer__quick-text">{this.quickOpenText}</span>
                        </div>
                    </div>
                )}
            </div>
        );
    },
});
