/**
 * Terminal 窗口管理器 - 通用组件
 * 管理多个终端窗口：拖拽、最小化、层叠等
 * 支持 SSH、K8s Pod、Docker Container 等多种终端类型
 */
import React, { useState, useCallback } from 'react';
import { Terminal } from 'lucide-react';
import { DraggableWindow } from '@/components/ui/draggable-window';
import type { ConnectionStatus, TerminalType } from './types';

/**
 * 终端窗口接口（泛型）
 */
export interface TerminalWindow<TResource = any> {
    id: string;
    resource: TResource;
    isMinimized: boolean;
    position: { x: number; y: number };
    size: { width: number; height: number };
    connectionStatus?: ConnectionStatus;
}

/**
 * 窗口管理器 Props
 */
interface TerminalWindowManagerProps<TResource = any> {
    /** 终端类型 */
    type: TerminalType;
    /** 获取窗口标题 */
    getWindowTitle: (resource: TResource) => string;
    /** 获取窗口副标题 */
    getWindowSubtitle: (resource: TResource) => string;
    /** 获取资源ID */
    getResourceId: (resource: TResource) => string | number;
    /** 渲染终端内容 */
    renderTerminal: (windowId: string, resource: TResource, callbacks: {
        onCloseReady: () => void;
        onStatusChange: (status: ConnectionStatus) => void;
    }) => React.ReactNode;
    /** 窗口打开回调 */
    onOpenWindow?: (windowId: string) => void;
}

export function TerminalWindowManager<TResource = any>({
    type,
    getWindowTitle,
    getWindowSubtitle,
    getResourceId,
    renderTerminal,
    onOpenWindow,
}: TerminalWindowManagerProps<TResource>) {
    const [windows, setWindows] = useState<TerminalWindow<TResource>[]>([]);
    const [activeWindowId, setActiveWindowId] = useState<string | null>(null);

    // 打开新窗口
    const openWindow = useCallback((resource: TResource) => {
        const resourceId = getResourceId(resource);
        const windowId = `${type}-${resourceId}-${Date.now()}`;
        const offset = windows.length * 30;
        
        // 计算居中位置
        const windowWidth = 1200;
        const windowHeight = 700;
        const centerX = (window.innerWidth - windowWidth) / 2 + offset;
        const centerY = (window.innerHeight - windowHeight) / 2 + offset;
        
        const newWindow: TerminalWindow<TResource> = {
            id: windowId,
            resource,
            isMinimized: false,
            position: { x: Math.max(0, centerX), y: Math.max(0, centerY) },
            size: { width: windowWidth, height: windowHeight },
            connectionStatus: 'connecting',
        };
        
        setWindows(prev => [...prev, newWindow]);
        setActiveWindowId(windowId);
        onOpenWindow?.(windowId);
        
        console.log(`✅ 打开${type.toUpperCase()}窗口: ${getWindowTitle(resource)} (${windowId})`);
    }, [windows.length, type, getWindowTitle, getResourceId, onOpenWindow]);

    // 真正关闭窗口
    const actuallyCloseWindow = useCallback((windowId: string) => {
        console.log(`❌ 真正关闭窗口: ${windowId}`);
        setWindows(prev => prev.filter(w => w.id !== windowId));
        if (activeWindowId === windowId) {
            setActiveWindowId(null);
        }
    }, [activeWindowId]);

    // 关闭窗口（优雅关闭）
    const closeWindow = useCallback((windowId: string) => {
        console.log(`🚪 准备关闭窗口: ${windowId}`);
        
        // 调用优雅关闭方法
        const closeMethod = (window as any)[`__closeSSH_${windowId}`];
        if (closeMethod && typeof closeMethod === 'function') {
            console.log('✅ 调用优雅关闭方法');
            closeMethod();
        } else {
            console.warn('⚠️ 未找到优雅关闭方法，直接关闭窗口');
            actuallyCloseWindow(windowId);
        }
    }, [actuallyCloseWindow]);

    // 最小化窗口
    const minimizeWindow = useCallback((windowId: string) => {
        setWindows(prev =>
            prev.map(w =>
                w.id === windowId ? { ...w, isMinimized: true } : w
            )
        );
        console.log(`➖ 最小化窗口: ${windowId}`);
    }, []);

    // 恢复窗口
    const restoreWindow = useCallback((windowId: string) => {
        setWindows(prev =>
            prev.map(w =>
                w.id === windowId ? { ...w, isMinimized: false } : w
            )
        );
        setActiveWindowId(windowId);
        console.log(`⬆️ 恢复窗口: ${windowId}`);
        
        // 触发resize事件，确保终端正确调整尺寸
        // 延迟100ms等待DOM更新完成
        setTimeout(() => {
            window.dispatchEvent(new Event('resize'));
        }, 100);
    }, []);

    // 激活窗口
    const focusWindow = useCallback((windowId: string) => {
        setActiveWindowId(windowId);
    }, []);

    // 更新窗口连接状态
    const updateWindowStatus = useCallback((windowId: string, status: ConnectionStatus) => {
        setWindows(prev =>
            prev.map(w =>
                w.id === windowId ? { ...w, connectionStatus: status } : w
            )
        );
    }, []);

    // 获取状态对应的按钮样式
    const getButtonStyle = (status?: ConnectionStatus) => {
        switch (status) {
            case 'connected':
                return 'bg-green-600 hover:bg-green-700';  // 绿色：已连接
            case 'connecting':
                return 'bg-yellow-600 hover:bg-yellow-700';  // 黄色：正在连接
            case 'reconnecting':
                return 'bg-orange-600 hover:bg-orange-700';  // 橙色：重连中
            case 'error':
                return 'bg-red-600 hover:bg-red-700';  // 红色：连接失败
            case 'disconnected':
                return 'bg-yellow-600 hover:bg-yellow-700';  // 黄色：已断开
            default:
                return 'bg-blue-600 hover:bg-blue-700';
        }
    };

    // 暴露 openWindow 方法给外部使用
    React.useEffect(() => {
        // 处理缩写词：ssh -> SSH, k8s -> K8s 等
        const typeMap: Record<string, string> = {
            'ssh': 'SSH',
            'k8s-pod': 'K8sPod',
            'docker-container': 'DockerContainer',
        };
        const typeName = typeMap[type] || type.charAt(0).toUpperCase() + type.slice(1);
        const globalKey = `__open${typeName}Window`;
        (window as any)[globalKey] = openWindow;
        
        console.log(`✅ 注册全局方法: ${globalKey}`);
        
        return () => {
            delete (window as any)[globalKey];
        };
    }, [openWindow, type]);

    return (
        <>
            {/* 渲染所有窗口 */}
            {windows.map(win => (
                <div
                    key={win.id}
                    style={{ 
                        visibility: win.isMinimized ? 'hidden' : 'visible',
                        pointerEvents: win.isMinimized ? 'none' : 'auto',
                    }}
                >
                    <DraggableWindow
                        id={win.id}
                        title={getWindowTitle(win.resource)}
                        onClose={() => closeWindow(win.id)}
                        onMinimize={() => minimizeWindow(win.id)}
                        isActive={activeWindowId === win.id}
                        onFocus={() => focusWindow(win.id)}
                        initialPosition={win.position}
                        initialSize={win.size}
                    >
                        {renderTerminal(win.id, win.resource, {
                            onCloseReady: () => actuallyCloseWindow(win.id),
                            onStatusChange: (status) => updateWindowStatus(win.id, status),
                        })}
                    </DraggableWindow>
                </div>
            ))}

            {/* 最小化的窗口悬浮按钮 */}
            {windows.filter(w => w.isMinimized).length > 0 && (
                <div className="fixed bottom-4 right-4 flex flex-col-reverse gap-2 z-[1001]">
                    {windows
                        .filter(w => w.isMinimized)
                        .map((win) => {
                            // 计算同一资源的窗口数量
                            const resourceId = getResourceId(win.resource);
                            const sameResourceWindows = windows.filter(w => getResourceId(w.resource) === resourceId);
                            const needsIndex = sameResourceWindows.length > 1;
                            const windowIndex = sameResourceWindows.findIndex(w => w.id === win.id) + 1;
                            
                            return (
                                <button
                                    key={win.id}
                                    className={`flex items-center gap-3 px-4 py-3 ${getButtonStyle(win.connectionStatus)} text-white rounded-lg shadow-lg transition-all hover:scale-105 hover:shadow-xl relative`}
                                    onClick={() => restoreWindow(win.id)}
                                    title={`恢复: ${getWindowSubtitle(win.resource)}${needsIndex ? ` #${windowIndex}` : ''}`}
                                >
                                    {/* 状态指示灯 */}
                                    <div className="absolute top-2 right-2">
                                        <div className={`h-2 w-2 rounded-full ${
                                            win.connectionStatus === 'connected' ? 'bg-white animate-pulse' :
                                            win.connectionStatus === 'error' || win.connectionStatus === 'disconnected' ? 'bg-white/70' :
                                            'bg-white/50 animate-pulse'
                                        }`} />
                                    </div>
                                    
                                    <Terminal className="h-5 w-5" />
                                    <div className="text-left">
                                        <div className="text-sm font-semibold flex items-center gap-2">
                                            <span>{getWindowSubtitle(win.resource)}</span>
                                            {needsIndex && (
                                                <span className="text-xs opacity-75">#{windowIndex}</span>
                                            )}
                                        </div>
                                        <div className="text-xs opacity-90">
                                            {type.toUpperCase()}
                                        </div>
                                    </div>
                                </button>
                            );
                        })}
                </div>
            )}
        </>
    );
}
