/**
 * Terminal 分屏视图 - 主组件
 * 管理分屏状态、键盘快捷键，并委托给 TerminalSplitNode 进行递归渲染
 */
import React, { useRef, useEffect } from 'react';
import { useSplitView } from './useSplitView';
import { TerminalSplitNode } from './TerminalSplitNode';
import type { TerminalTab, TerminalConnectionConfig, TerminalAuditConfig, TerminalToolbarConfig, SplitNode, ConnectionStatus } from './types';

// 对外暴露的主组件Props
export interface TerminalSplitViewProps {
    initialTab: TerminalTab;
    getConnectionConfig: (tab: TerminalTab) => TerminalConnectionConfig;
    getAuditConfig: () => TerminalAuditConfig;
    getToolbarConfig: () => TerminalToolbarConfig;
    onCloseAllReady?: (closeAllFn: () => void) => void;  // 暴露closeAll函数给外部
    onWindowClose?: () => void;  // 最后一个Tab关闭时，通知关闭整个窗口
    onStatusChange?: (status: ConnectionStatus) => void;  // 当前激活Tab的连接状态变化
}

/**
 * Terminal 分屏视图 - 主组件
 * 职责：
 * 1. 管理分屏状态（通过 useSplitView hook）
 * 2. 处理键盘快捷键
 * 3. 暴露 closeAll 方法供外部调用
 * 4. 委托给 TerminalSplitNode 进行递归渲染
 */
export const TerminalSplitView: React.FC<TerminalSplitViewProps> = ({
    initialTab,
    getConnectionConfig,
    getAuditConfig,
    getToolbarConfig,
    onCloseAllReady,
    onWindowClose,
    onStatusChange,
}) => {
    const {
        layout,
        activeGroupId,
        splitUp,
        splitDown,
        splitLeft,
        splitRight,
        splitInGroup,
        switchTab,
        closeTab,
        closeAll,
        resizeGroups,
        setActiveGroupId,
    } = useSplitView({ initialTab, onWindowClose });

    // 使用useRef追踪所有Tab的连接状态，避免无限循环
    const tabStatusesRef = useRef<Map<string, ConnectionStatus>>(new Map());
    const lastReportedStatusRef = useRef<{tabId: string | null, status: ConnectionStatus | null}>({ tabId: null, status: null });
    const onStatusChangeRef = useRef(onStatusChange);
    
    // 保持onStatusChange引用最新
    useEffect(() => {
        onStatusChangeRef.current = onStatusChange;
    }, [onStatusChange]);
    
    // 找到当前激活的Tab ID (不使用useCallback，直接定义)
    const findActiveTabId = (node: SplitNode, targetGroupId: string): string | null => {
        if (node.type === 'group' && node.id === targetGroupId) {
            const activeTab = node.tabs.find(tab => tab.isActive);
            return activeTab?.id || null;
        }
        if (node.type === 'container') {
            for (const child of node.children) {
                const result = findActiveTabId(child, targetGroupId);
                if (result) return result;
            }
        }
        return null;
    };

    // 当Terminal状态变化时的回调 - 使用稳定的引用
    const handleTerminalStatusChange = React.useCallback((tabId: string, status: ConnectionStatus) => {
        // 更新状态映射
        tabStatusesRef.current.set(tabId, status);
        
        // 使用ref获取最新的layout和activeGroupId，避免依赖导致重建
        const activeTabId = findActiveTabId(layout.root, activeGroupId);
        if (activeTabId === tabId && onStatusChangeRef.current) {
            // 只有状态真正变化时才报告
            const lastReported = lastReportedStatusRef.current;
            if (lastReported.tabId !== tabId || lastReported.status !== status) {
                lastReportedStatusRef.current = { tabId, status };
                onStatusChangeRef.current(status);
            }
        }
    }, []); // 空依赖，永远不重新创建

    // 当激活Tab变化时，报告新激活Tab的状态
    useEffect(() => {
        const activeTabId = findActiveTabId(layout.root, activeGroupId);
        if (activeTabId && onStatusChangeRef.current) {
            const status = tabStatusesRef.current.get(activeTabId) || 'connecting';
            const lastReported = lastReportedStatusRef.current;
            // 只有Tab或状态变化时才报告
            if (lastReported.tabId !== activeTabId || lastReported.status !== status) {
                lastReportedStatusRef.current = { tabId: activeTabId, status };
                onStatusChangeRef.current(status);
            }
        }
    }, [activeGroupId, layout.root]);

    // 暴露closeAll方法给外部
    useEffect(() => {
        if (onCloseAllReady) {
            onCloseAllReady(closeAll);
        }
    }, [onCloseAllReady, closeAll]);

    // 快捷键支持
    useEffect(() => {
        const handleKeyDown = (e: KeyboardEvent) => {
            // Cmd/Ctrl + \ - 向右拆分
            if ((e.metaKey || e.ctrlKey) && e.key === '\\') {
                e.preventDefault();
                splitRight();
            }
            // Cmd/Ctrl + Shift + 方向键 - 向指定方向拆分
            if ((e.metaKey || e.ctrlKey) && e.shiftKey) {
                if (e.key === 'ArrowUp') {
                    e.preventDefault();
                    splitUp();
                } else if (e.key === 'ArrowDown') {
                    e.preventDefault();
                    splitDown();
                } else if (e.key === 'ArrowLeft') {
                    e.preventDefault();
                    splitLeft();
                } else if (e.key === 'ArrowRight') {
                    e.preventDefault();
                    splitRight();
                }
            }
        };

        window.addEventListener('keydown', handleKeyDown);
        return () => window.removeEventListener('keydown', handleKeyDown);
    }, [splitUp, splitDown, splitLeft, splitRight]);

    // 计算是否有多个分屏组
    const countGroups = (node: SplitNode): number => {
        if (node.type === 'group') return 1;
        return node.children.reduce((sum, child) => sum + countGroups(child), 0);
    };
    const hasMultipleGroups = countGroups(layout.root) > 1;

    return (
        <div className="terminal-split-container h-full w-full">
            <TerminalSplitNode
                node={layout.root}
                activeGroupId={activeGroupId}
                onTabClick={switchTab}
                onTabClose={closeTab}
                onNewTab={splitInGroup}
                onSplitUp={splitUp}
                onSplitDown={splitDown}
                onSplitLeft={splitLeft}
                onSplitRight={splitRight}
                onFocus={setActiveGroupId}
                onResize={resizeGroups}
                getConnectionConfig={getConnectionConfig}
                getAuditConfig={getAuditConfig}
                getToolbarConfig={getToolbarConfig}
                hasMultipleGroups={hasMultipleGroups}
                onTerminalStatusChange={handleTerminalStatusChange}
            />
        </div>
    );
};
