/**
 * SSH 窗口管理器
 * 使用 TerminalSplitView 支持分屏功能
 */
import React, { useEffect, useRef } from 'react';
import { 
    TerminalWindowManager,
    TerminalSplitView,
    type TerminalTab,
    type TerminalConnectionConfig,
    type TerminalAuditConfig,
    type TerminalToolbarConfig,
    type ConnectionStatus,
} from '@/components/Terminal';
import type { ServerResponse } from '../types';

/**
 * SSH Terminal 分屏视图包装器
 * 负责注册优雅关闭方法到window对象
 */
interface SSHTerminalSplitViewWrapperProps {
    windowId: string;
    initialTab: TerminalTab;
    getConnectionConfig: (tab: TerminalTab) => TerminalConnectionConfig;
    getAuditConfig: () => TerminalAuditConfig;
    getToolbarConfig: () => TerminalToolbarConfig;
    onCloseReady: () => void;
    onStatusChange?: (status: ConnectionStatus) => void;
}

const SSHTerminalSplitViewWrapper: React.FC<SSHTerminalSplitViewWrapperProps> = ({
    windowId,
    initialTab,
    getConnectionConfig,
    getAuditConfig,
    getToolbarConfig,
    onCloseReady,
    onStatusChange,
}) => {
    const closeAllRef = useRef<(() => void) | null>(null);
    const onCloseReadyRef = useRef(onCloseReady);
    const onStatusChangeRef = useRef(onStatusChange);
    
    // 保持最新的回调引用
    useEffect(() => {
        onCloseReadyRef.current = onCloseReady;
    }, [onCloseReady]);
    
    useEffect(() => {
        onStatusChangeRef.current = onStatusChange;
    }, [onStatusChange]);

    // 注册优雅关闭方法到window对象
    useEffect(() => {
        const closeMethodName = `__closeSSH_${windowId}`;
        (window as any)[closeMethodName] = () => {
            console.log(`[SSHTerminalSplitViewWrapper] 调用优雅关闭方法: ${windowId}`);
            // 先关闭所有连接
            if (closeAllRef.current) {
                closeAllRef.current();
            }
            // 再通知窗口可以关闭
            onCloseReadyRef.current();
        };
        console.log(`[SSHTerminalSplitViewWrapper] 注册优雅关闭方法: ${closeMethodName}`);

        return () => {
            delete (window as any)[closeMethodName];
            console.log(`[SSHTerminalSplitViewWrapper] 注销优雅关闭方法: ${closeMethodName}`);
        };
    }, [windowId]); // 只依赖windowId，不依赖onCloseReady

    // 使用稳定的回调引用
    const stableOnWindowClose = React.useCallback(() => {
        onCloseReadyRef.current();
    }, []);
    
    const stableOnStatusChange = React.useCallback((status: ConnectionStatus) => {
        onStatusChangeRef.current?.(status);
    }, []);

    return (
        <TerminalSplitView
            initialTab={initialTab}
            getConnectionConfig={getConnectionConfig}
            getAuditConfig={getAuditConfig}
            getToolbarConfig={getToolbarConfig}
            onCloseAllReady={(closeAllFn) => {
                // 保存closeAll函数到ref
                closeAllRef.current = closeAllFn;
            }}
            onWindowClose={stableOnWindowClose}
            onStatusChange={stableOnStatusChange}
        />
    );
};

interface SSHWindowManagerProps {
    onOpenWindow?: (windowId: string) => void;
}

export const SSHWindowManager: React.FC<SSHWindowManagerProps> = ({ onOpenWindow }) => {
    return (
        <TerminalWindowManager<ServerResponse>
            type="ssh"
            getWindowTitle={(server) => `SSH终端 - ${server.serverName} (${server.hostIp})`}
            getWindowSubtitle={(server) => server.serverName}
            getResourceId={(server) => server.id}
            renderTerminal={(windowId, server, { onCloseReady, onStatusChange }) => {
                // 创建初始 Tab
                const initialTab: TerminalTab = {
                    id: `tab-${Date.now()}`,
                    title: `${server.serverName} - ${server.hostIp}`,
                    serverId: server.id,
                    serverName: server.serverName,
                    isActive: true,
                };

                // 连接配置函数
                const getConnectionConfig = (tab: TerminalTab): TerminalConnectionConfig => {
                    const token = localStorage.getItem('token');
                    return {
                        type: 'ssh',
                        serverId: tab.serverId,
                        serverName: server.serverName,
                        hostIp: server.hostIp,
                        token: token || undefined,
                        autoReconnect: true,
                        reconnectInterval: 3000,
                        maxReconnectAttempts: 5,
                    };
                };

                // 审计配置
                const getAuditConfig = (): TerminalAuditConfig => ({
                    enabled: true,
                    companyName: '链宇技术有限公司',
                });

                // 工具栏配置
                const getToolbarConfig = (): TerminalToolbarConfig => ({
                    show: true,
                    showSearch: true,
                    showClear: true,
                    showCopy: true,
                    showFontSize: true,
                    showStatus: true,
                    showFontSizeLabel: true,
                });

                return (
                    <SSHTerminalSplitViewWrapper
                        windowId={windowId}
                        initialTab={initialTab}
                        getConnectionConfig={getConnectionConfig}
                        getAuditConfig={getAuditConfig}
                        getToolbarConfig={getToolbarConfig}
                        onCloseReady={onCloseReady}
                        onStatusChange={onStatusChange}
                    />
                );
            }}
            onOpenWindow={onOpenWindow}
        />
    );
};

// 保留类型定义以兼容现有代码
export interface SSHWindow {
    id: string;
    server: ServerResponse;
    isMinimized: boolean;
    position: { x: number; y: number };
    size: { width: number; height: number };
    connectionStatus?: 'connecting' | 'connected' | 'reconnecting' | 'disconnected' | 'error';
}
