/**
 * Terminal 组件 - 通用终端
 * 支持 SSH、K8s Pod、Docker Container 等多种场景
 */
import React, { useState, useEffect, useCallback, useRef } from 'react';
import { Input } from '@/components/ui/input';
import 'xterm/css/xterm.css';
import styles from './index.module.less';
import { TerminalToolbar } from './TerminalToolbar';
import type { TerminalProps, TerminalToolbarConfig } from './types';
import { TERMINAL_THEMES, getThemeByName } from './themes';
import { Loader2, XCircle, ChevronUp, ChevronDown, X, WifiOff } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { message } from 'antd';
import { TerminalInstanceManager } from './core/TerminalInstanceManager';
import type { ConnectionStatus } from './strategies/BaseConnectionStrategy';

export const Terminal: React.FC<TerminalProps> = ({
    id,
    connection,
    display,
    audit,
    toolbar,
    isActive,
    compact = false,
    onStatusChange,
    onCloseReady,
    onError,
    onSplitUp,
    onSplitDown,
    onSplitLeft,
    onSplitRight,
    onSplitInGroup,
}) => {
    const terminalRef = useRef<HTMLDivElement>(null);
    const wrapperRef = useRef<HTMLDivElement>(null);  // 最外层容器
    const instanceRef = useRef<ReturnType<TerminalInstanceManager['getOrCreate']> | null>(null);
    
    const [fontSize, setFontSize] = useState(display?.fontSize ?? 14);
    const [showSearch, setShowSearch] = useState(false);
    const [currentTheme, setCurrentTheme] = useState('dark');
    const [auditShown, setAuditShown] = useState(false);
    const [connectionStatus, setConnectionStatus] = useState<ConnectionStatus>('connecting');  // 初始状态为连接中，符合正常生命周期
    const [errorMessage, setErrorMessage] = useState<string>('');
    const [connectedTime, setConnectedTime] = useState<Date | null>(null);

    // 默认工具栏配置
    const toolbarConfig: TerminalToolbarConfig = {
        show: toolbar?.show ?? true,
        showSearch: toolbar?.showSearch ?? true,
        showClear: toolbar?.showClear ?? true,
        showCopy: toolbar?.showCopy ?? true,
        showFontSize: toolbar?.showFontSize ?? true,
        showStatus: toolbar?.showStatus ?? true,
        showFontSizeLabel: toolbar?.showFontSizeLabel ?? true,
        extraActions: toolbar?.extraActions,
    };

    // 初始化 Terminal 实例
    useEffect(() => {
        const manager = TerminalInstanceManager.getInstance();
        
        // 获取或创建实例（Manager 内部会处理连接策略的创建和复用）
        const instance = manager.getOrCreate(id, {
            id,
            connectionConfig: connection,  // 传配置，不传策略实例
            display: {
                ...display,
                fontSize,
                theme: getThemeByName(currentTheme).theme,
            },
        });
        
        instanceRef.current = instance;
        
        // 立即同步当前状态（避免初始状态不一致导致闪烁）
        const currentState = instance.getState();
        setConnectionStatus(currentState.status);
        if (currentState.errorMessage) {
            setErrorMessage(currentState.errorMessage);
        }
        
        // 挂载到 DOM
        if (terminalRef.current) {
            instance.mount(terminalRef.current);
        }
        
        // 订阅状态变化
        const unsubscribe = instance.onStateChange((state) => {
            setConnectionStatus(state.status);
            setErrorMessage(state.errorMessage || '');
            
            // 记录连接成功时间
            if (state.status === 'connected' && !connectedTime) {
                setConnectedTime(new Date());
            } else if (state.status === 'disconnected' || state.status === 'error') {
                setConnectedTime(null);
            }
            
            onStatusChange?.(state.status);
            if (state.errorMessage) {
                onError?.(state.errorMessage);
            }
        });
        
        // 延迟连接（仅在未连接或需要连接时）
        const timer = setTimeout(() => {
            const currentState = instance.getState();
            // 在 connecting、disconnected 或 error 状态下需要建立连接
            if (currentState.status === 'connecting' || currentState.status === 'disconnected' || currentState.status === 'error') {
                instance.connect();
            }
        }, 300);

        return () => {
            clearTimeout(timer);
            unsubscribe();
            instance.unmount();
            // 注意：不调用 manager.destroy()，实例会被复用
        };
    }, [id]);

    // 监听Tab激活状态，激活时调整尺寸并通知后端
    useEffect(() => {
        if (isActive && instanceRef.current) {
            setTimeout(() => {
                const fitAddon = instanceRef.current?.getFitAddon();
                if (fitAddon && instanceRef.current) {
                    fitAddon.fit();
                    // 发送新的尺寸给后端
                    const xterm = instanceRef.current.getXTerm();
                    const cols = xterm.cols;
                    const rows = xterm.rows;
                    instanceRef.current.sendResize(cols, rows);
                    // 重要：让XTerm获取焦点，否则无法输入
                    xterm.focus();
                }
            }, 100);
        }
    }, [isActive, id]);

    // 监听窗口大小变化，自动调整终端尺寸
    useEffect(() => {
        const handleResize = () => {
            const fitAddon = instanceRef.current?.getFitAddon();
            if (fitAddon) {
                setTimeout(() => {
                    fitAddon.fit();
                }, 100);
            }
        };

        window.addEventListener('resize', handleResize);
        
        return () => {
            window.removeEventListener('resize', handleResize);
        };
    }, []);

    // 显示审计警告（委托给TerminalInstance，确保只显示一次）
    useEffect(() => {
        if (connectionStatus === 'connected' && audit?.enabled && instanceRef.current) {
            const instance = instanceRef.current;
            const companyName = audit.companyName || '';
            const customMessage = audit.message;

            // 使用TerminalInstance的showAudit方法，自动处理去重
            const shown = instance.showAudit(companyName, customMessage);
            if (shown) {
                setAuditShown(true);  // 更新组件状态（可选，仅用于UI反馈）
            }
        }
    }, [connectionStatus, audit]);

    // 重连处理
    const handleReconnect = useCallback(() => {
        if (instanceRef.current) {
            instanceRef.current.disconnect();
            instanceRef.current.resetAudit(); // 重置审计警告标记
            setAuditShown(false);
            setTimeout(() => {
                instanceRef.current?.connect();
            }, 100);
        }
    }, []);

    // 搜索
    const [searchQuery, setSearchQuery] = useState('');
    
    const handleSearch = useCallback(() => {
        setShowSearch(!showSearch);
        if (!showSearch) {
            // 打开搜索时聚焦输入框
            setTimeout(() => {
                const input = document.querySelector('.terminal-search-input') as HTMLInputElement;
                input?.focus();
            }, 100);
        }
    }, [showSearch]);

    const handleSearchChange = useCallback((value: string) => {
        setSearchQuery(value);
        const searchAddon = instanceRef.current?.getSearchAddon();
        if (searchAddon) {
            searchAddon.findNext(value, { incremental: true });
        }
    }, []);

    const handleSearchNext = useCallback(() => {
        const searchAddon = instanceRef.current?.getSearchAddon();
        if (searchAddon && searchQuery) {
            searchAddon.findNext(searchQuery);
        }
    }, [searchQuery]);

    const handleSearchPrev = useCallback(() => {
        const searchAddon = instanceRef.current?.getSearchAddon();
        if (searchAddon && searchQuery) {
            searchAddon.findPrevious(searchQuery);
        }
    }, [searchQuery]);

    const handleCloseSearch = useCallback(() => {
        setShowSearch(false);
        setSearchQuery('');
        instanceRef.current?.getSearchAddon()?.clearDecorations();
    }, []);

    // 清屏
    const handleClear = useCallback(() => {
        if (instanceRef.current) {
            instanceRef.current.clear();
            message.success('终端已清屏');
        }
    }, []);

    // 复制
    const handleCopy = useCallback(() => {
        if (instanceRef.current) {
            const selection = instanceRef.current.getSelection();
            if (selection) {
                navigator.clipboard.writeText(selection);
                message.success('已复制到剪贴板');
            } else {
                message.warning('请先选中要复制的内容');
            }
        }
    }, []);

    // 放大字体
    const handleZoomIn = useCallback(() => {
        const newSize = Math.min(fontSize + 2, 32);
        setFontSize(newSize);
        if (instanceRef.current) {
            instanceRef.current.updateDisplay({ fontSize: newSize });
        }
    }, [fontSize]);

    // 缩小字体
    const handleZoomOut = useCallback(() => {
        const newSize = Math.max(fontSize - 2, 10);
        setFontSize(newSize);
        if (instanceRef.current) {
            instanceRef.current.updateDisplay({ fontSize: newSize });
        }
    }, [fontSize]);

    // 切换主题
    const handleThemeChange = useCallback((themeName: string) => {
        setCurrentTheme(themeName);
        if (instanceRef.current) {
            const theme = getThemeByName(themeName);
            instanceRef.current.updateDisplay({ theme: theme.theme });
            message.success(`已切换到 ${theme.label} 主题`);
        }
    }, []);

    // 打开文件管理器（调用全局方法）
    const handleFileManager = useCallback(() => {
        if (connection.type !== 'ssh') {
            message.warning('文件管理仅支持SSH连接');
            return;
        }
        if (!connection.serverId || !connection.serverName) {
            message.error('缺少服务器信息');
            return;
        }
        // 调用全局方法打开文件管理器
        const openFileManager = (window as any).openFileManager;
        if (openFileManager) {
            openFileManager(Number(connection.serverId), connection.serverName);
        } else {
            message.error('文件管理器未初始化');
        }
    }, [connection.type, connection.serverId, connection.serverName]);

    return (
        <div ref={wrapperRef} className={styles.terminalWrapper}>
            {/* 工具栏 */}
            <TerminalToolbar
                config={toolbarConfig}
                connectionStatus={connectionStatus}
                serverName={connection.serverName}
                hostIp={connection.hostIp}
                connectedTime={connectedTime}
                fontSize={fontSize}
                currentTheme={currentTheme}
                themes={TERMINAL_THEMES}
                compact={compact}
                onSearch={handleSearch}
                onClear={handleClear}
                onCopy={handleCopy}
                onZoomIn={handleZoomIn}
                onZoomOut={handleZoomOut}
                onReconnect={handleReconnect}
                onThemeChange={handleThemeChange}
                onFileManager={connection.type === 'ssh' ? handleFileManager : undefined}
                onSplitUp={onSplitUp}
                onSplitDown={onSplitDown}
                onSplitLeft={onSplitLeft}
                onSplitRight={onSplitRight}
                onSplitInGroup={onSplitInGroup}
            />

            {/* 终端区域 */}
            <div className={styles.container}>
                {/* 搜索框 */}
                {showSearch && (
                    <div className={styles.searchBar}>
                        <Input
                            type="text"
                            placeholder="搜索..."
                            value={searchQuery}
                            onChange={(e) => handleSearchChange(e.target.value)}
                            onKeyDown={(e) => {
                                if (e.key === 'Enter') {
                                    if (e.shiftKey) {
                                        handleSearchPrev();
                                    } else {
                                        handleSearchNext();
                                    }
                                } else if (e.key === 'Escape') {
                                    handleCloseSearch();
                                }
                            }}
                            className="terminal-search-input"
                            style={{
                                background: 'transparent',
                                border: 'none',
                                outline: 'none',
                                color: '#fff',
                                width: '200px',
                                fontSize: '0.875rem',
                            }}
                        />
                        <div className="flex items-center gap-0.5 ml-1">
                            <Button
                                size="sm"
                                variant="ghost"
                                className="h-7 px-2"
                                onClick={handleSearchPrev}
                                title="上一个 (Shift+Enter)"
                            >
                                <ChevronUp className="h-3.5 w-3.5" />
                            </Button>
                            <Button
                                size="sm"
                                variant="ghost"
                                className="h-7 px-2"
                                onClick={handleSearchNext}
                                title="下一个 (Enter)"
                            >
                                <ChevronDown className="h-3.5 w-3.5" />
                            </Button>
                        </div>
                        <Button
                            size="sm"
                            variant="ghost"
                            className="h-7 px-2"
                            onClick={handleCloseSearch}
                            title="关闭 (Esc)"
                        >
                            <X className="h-3.5 w-3.5" />
                        </Button>
                    </div>
                )}

                <div
                    ref={terminalRef}
                    className={styles.content}
                />

                {/* 连接中 */}
                {connectionStatus === 'connecting' && (
                    <div className={`${styles.statusOverlay} ${styles.connecting}`}>
                        <Loader2 className={`${styles.statusIcon} animate-spin`} />
                        <p className={styles.statusText}>正在连接...</p>
                    </div>
                )}

                {/* 重连中 */}
                {connectionStatus === 'reconnecting' && (
                    <div className={`${styles.statusOverlay} ${styles.reconnecting}`}>
                        <Loader2 className={`${styles.statusIcon} animate-spin`} />
                        <p className={styles.statusText}>连接中断，正在重连...</p>
                    </div>
                )}

                {/* 已断开连接 */}
                {connectionStatus === 'disconnected' && (
                    <div className={`${styles.statusOverlay} ${styles.disconnected}`}>
                        <WifiOff className={styles.statusIcon} />
                        <p className={styles.statusText}>已断开连接</p>
                        {errorMessage && (
                            <p className={styles.statusDetail}>{errorMessage}</p>
                        )}
                        <Button onClick={handleReconnect} variant="outline">
                            重新连接
                        </Button>
                    </div>
                )}

                {/* 错误 */}
                {connectionStatus === 'error' && (
                    <div className={`${styles.statusOverlay} ${styles.error}`}>
                        <XCircle className={styles.statusIcon} />
                        <p className={styles.statusText}>连接失败</p>
                        {errorMessage && (
                            <p className={styles.statusDetail}>{errorMessage}</p>
                        )}
                        <Button onClick={handleReconnect} variant="outline">
                            重新连接
                        </Button>
                    </div>
                )}
            </div>

            {/* 文件管理器已移至独立的窗口管理器 */}
        </div>
    );
};
