/**
 * Terminal 分屏节点渲染器
 * 负责递归渲染分屏树的每个节点（Group 或 Container）
 */
import React from 'react';
import { Terminal } from './Terminal';
import { TerminalSplitDivider } from './TerminalSplitDivider';
import { X, Plus } from 'lucide-react';
import type { SplitNode, TerminalTab, TerminalConnectionConfig, TerminalAuditConfig, TerminalToolbarConfig, ConnectionStatus } from './types';

/**
 * 分屏节点渲染器 Props
 */
export interface TerminalSplitNodeProps {
    node: SplitNode;
    activeGroupId: string;
    onTabClick: (groupId: string, tabId: string) => void;
    onTabClose: (groupId: string, tabId: string) => void;
    onNewTab: (groupId?: string) => void;
    onSplitUp: () => void;
    onSplitDown: () => void;
    onSplitLeft: () => void;
    onSplitRight: () => void;
    onFocus: (groupId: string) => void;
    onResize: (nodeId: string, delta: number, containerSize?: number) => void;
    getConnectionConfig: (tab: TerminalTab) => TerminalConnectionConfig;
    getAuditConfig: () => TerminalAuditConfig;
    getToolbarConfig: () => TerminalToolbarConfig;
    hasMultipleGroups?: boolean;  // 是否有多个分屏组
    onTerminalStatusChange?: (tabId: string, status: ConnectionStatus) => void;  // Terminal状态变化回调
}

/**
 * 递归渲染分屏节点
 * - Group 节点：渲染 Tab 栏和 Terminal
 * - Container 节点：递归渲染子节点，插入分隔条
 */
const TerminalSplitNodeComponent: React.FC<TerminalSplitNodeProps> = ({
    node,
    activeGroupId,
    onTabClick,
    onTabClose,
    onNewTab,
    onSplitUp,
    onSplitDown,
    onSplitLeft,
    onSplitRight,
    onFocus,
    onResize,
    getConnectionConfig,
    getAuditConfig,
    getToolbarConfig,
    hasMultipleGroups = false,
    onTerminalStatusChange,
}) => {
    // 渲染 Group 节点（包含 Tabs 和 Terminal）
    if (node.type === 'group') {
        const isActive = node.id === activeGroupId;
        const connectionConfigs: Record<string, TerminalConnectionConfig> = {};
        node.tabs.forEach(tab => {
            connectionConfigs[tab.id] = getConnectionConfig(tab);
        });
        const auditConfig = getAuditConfig();
        const toolbarConfig = getToolbarConfig();

        return (
            <div 
                className="h-full w-full flex flex-col bg-white dark:bg-gray-900"
                onClick={() => {
                    onFocus(node.id);
                }}
            >
                {/* Tab栏 */}
                <div className="flex-shrink-0 border-b border-gray-200 dark:border-gray-700">
                    <div className="flex items-center px-2 py-1 gap-1 overflow-x-auto">
                        {node.tabs.map((tab) => (
                            <div
                                key={tab.id}
                                className={`flex items-center gap-1 px-3 py-1.5 rounded-t cursor-pointer transition-colors ${
                                    tab.isActive
                                        ? 'bg-gray-100 dark:bg-gray-800 border-b-2 border-blue-500'
                                        : 'hover:bg-gray-50 dark:hover:bg-gray-800/50'
                                }`}
                                onClick={(e) => {
                                    e.stopPropagation();
                                    onTabClick(node.id, tab.id);
                                }}
                            >
                                <span className="text-xs truncate max-w-[150px]" title={tab.title}>
                                    {tab.serverName}
                                </span>
                                <button
                                    className="hover:bg-gray-300 dark:hover:bg-gray-600 rounded p-0.5"
                                    onClick={(e) => {
                                        e.stopPropagation();
                                        onTabClose(node.id, tab.id);
                                    }}
                                >
                                    <X className="h-3 w-3" />
                                </button>
                            </div>
                        ))}
                        <button
                            className="flex items-center justify-center w-8 h-8 hover:bg-gray-200 dark:hover:bg-gray-700 rounded"
                            onClick={(e) => {
                                e.stopPropagation();
                                onNewTab(node.id);  // 直接传递groupId
                            }}
                            title="新建终端 (Cmd+T)"
                        >
                            <Plus className="h-3.5 w-3.5" />
                        </button>
                    </div>
                </div>

                {/* 终端内容 */}
                <div className="flex-1 overflow-hidden relative">
                    {node.tabs.map((tab) => (
                        <div
                            key={tab.id}
                            className="absolute inset-0"
                            style={{ display: tab.isActive ? 'block' : 'none' }}
                        >
                            <Terminal
                                id={tab.id}
                                connection={connectionConfigs[tab.id]}
                                audit={auditConfig}
                                toolbar={toolbarConfig}
                                isActive={tab.isActive}
                                compact={hasMultipleGroups}
                                onStatusChange={(status) => onTerminalStatusChange?.(tab.id, status)}
                                onSplitUp={onSplitUp}
                                onSplitDown={onSplitDown}
                                onSplitLeft={onSplitLeft}
                                onSplitRight={onSplitRight}
                                onSplitInGroup={onNewTab}
                            />
                        </div>
                    ))}
                </div>
            </div>
        );
    }

    // 渲染 Container 节点（递归渲染子节点）
    const isHorizontal = node.orientation === 'horizontal';
    
    return (
        <div className={`h-full w-full flex ${isHorizontal ? 'flex-row' : 'flex-col'}`}>
            {node.children.map((child, index) => (
                <React.Fragment key={child.id}>
                    <div
                        className="flex-shrink-0 flex-grow-0"
                        style={{
                            [isHorizontal ? 'width' : 'height']: `${child.size}%`,
                        }}
                    >
                        {/* 递归渲染子节点 */}
                        <TerminalSplitNodeComponent
                            node={child}
                            activeGroupId={activeGroupId}
                            onTabClick={onTabClick}
                            onTabClose={onTabClose}
                            onNewTab={onNewTab}
                            onSplitUp={onSplitUp}
                            onSplitDown={onSplitDown}
                            onSplitLeft={onSplitLeft}
                            onSplitRight={onSplitRight}
                            onFocus={onFocus}
                            onResize={onResize}
                            getConnectionConfig={getConnectionConfig}
                            getAuditConfig={getAuditConfig}
                            getToolbarConfig={getToolbarConfig}
                            hasMultipleGroups={hasMultipleGroups}
                            onTerminalStatusChange={onTerminalStatusChange}
                        />
                    </div>

                    {/* 分隔条 - 不在最后一个节点之后显示 */}
                    {index < node.children.length - 1 && (
                        <TerminalSplitDivider
                            orientation={node.orientation}
                            onResize={(delta, containerSize) => onResize(child.id, delta, containerSize)}
                        />
                    )}
                </React.Fragment>
            ))}
        </div>
    );
};

/**
 * 使用 React.memo 优化性能
 * 只在 props 变化时才重新渲染
 */
export const TerminalSplitNode = React.memo(TerminalSplitNodeComponent);
