import React, { useState, useEffect } from 'react';
import {
    Server,
    Plus,
    Settings,
    Activity,
    AlertCircle,
    HelpCircle,
    Monitor,
    Apple,
    Filter,
    Search,
    RotateCcw,
    Grid3x3,
    List,
    Bell,
} from 'lucide-react';
import { Card, CardHeader, CardContent } from '@/components/ui/card';
import { Separator } from '@/components/ui/separator';
import { Skeleton } from '@/components/ui/skeleton';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Button } from '@/components/ui/button';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import {
    TooltipProvider,
} from '@/components/ui/tooltip';
import { ConfirmDialog } from '@/components/ui/confirm-dialog';
import { useToast } from '@/components/ui/use-toast';
import { DataTablePagination } from '@/components/ui/pagination';
import { Input } from '@/components/ui/input';
import type { ServerResponse, ServerCategoryResponse, ServerStatus, OsType } from './types';
import { ServerStatusLabels, OsTypeLabels } from './types';
import { getServers, getServerList, getServerCategories, deleteServer, testServerConnection, collectServerHardware } from './service';
import { CategoryManageDialog } from './components/CategoryManageDialog';
import { AlertRuleManageDialog } from './components/AlertRuleManageDialog';
import { ServerEditDialog } from './components/ServerEditDialog';
import { ServerCard } from './components/ServerCard';
import { ServerTable } from './components/ServerTable';
import { SSHWindowManager } from './components/SSHWindowManager';
import { FileManagerWindowManager } from '@/components/FileManager';
import { ServerMonitorDialog } from './components/ServerMonitorDialog';

const ServerList: React.FC = () => {
    const { toast } = useToast();

    // 视图模式
    type ViewMode = 'grid' | 'table';
    const [viewMode, setViewMode] = useState<ViewMode>('grid');

    // 搜索关键字
    const [searchKeyword, setSearchKeyword] = useState<string>('');

    // 状态管理
    const [categories, setCategories] = useState<ServerCategoryResponse[]>([]);
    const [servers, setServers] = useState<ServerResponse[]>([]);
    const [loading, setLoading] = useState(false);
    const [pageLoading, setPageLoading] = useState(false); // 分页加载状态
    const [pageIndex, setPageIndex] = useState(0);
    const [pageSize] = useState(10);
    const [totalElements, setTotalElements] = useState(0);
    // 筛选条件 - 实际应用的
    const [selectedCategoryId, setSelectedCategoryId] = useState<number | undefined>();
    const [selectedStatus, setSelectedStatus] = useState<ServerStatus | undefined>();
    const [selectedOsType, setSelectedOsType] = useState<OsType | undefined>();

    // 筛选条件 - 临时输入的（未提交）
    const [tempCategoryId, setTempCategoryId] = useState<number | undefined>();
    const [tempStatus, setTempStatus] = useState<ServerStatus | undefined>();
    const [tempOsType, setTempOsType] = useState<OsType | undefined>();

    const [categoryDialogOpen, setCategoryDialogOpen] = useState(false);
    const [alertRuleDialogOpen, setAlertRuleDialogOpen] = useState(false);
    const [editDialogOpen, setEditDialogOpen] = useState(false);
    const [editingServer, setEditingServer] = useState<ServerResponse | null>(null);
    const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
    const [serverToDelete, setServerToDelete] = useState<ServerResponse | null>(null);
    const [testingServerId, setTestingServerId] = useState<number | null>(null);
    const [collectingServerId, setCollectingServerId] = useState<number | null>(null);
    const [monitorDialogOpen, setMonitorDialogOpen] = useState(false);
    const [monitoringServer, setMonitoringServer] = useState<ServerResponse | null>(null);
    const [statsData, setStatsData] = useState<{
        total: number;
        online: number;
        offline: number;
        unknown: number;
    }>({ total: 0, online: 0, offline: 0, unknown: 0 });

    // 加载分类列表
    const loadCategories = async () => {
        try {
            const data = await getServerCategories();
            setCategories(data || []);
        } catch (error) {
            console.error('加载分类失败:', error);
        }
    };

    // 加载统计数据 - 从后端获取各状态数量（如果后端没有统计接口,暂时显示总数）
    const loadStats = async () => {
        try {
            // 并行请求各个状态的数量
            const [totalResult, onlineResult, offlineResult, unknownResult] = await Promise.all([
                getServers({ categoryId: selectedCategoryId, osType: selectedOsType, pageNum: 0, pageSize: 1 }),
                getServers({ categoryId: selectedCategoryId, status: 'ONLINE', osType: selectedOsType, pageNum: 0, pageSize: 1 }),
                getServers({ categoryId: selectedCategoryId, status: 'OFFLINE', osType: selectedOsType, pageNum: 0, pageSize: 1 }),
                getServers({ categoryId: selectedCategoryId, status: 'UNKNOWN', osType: selectedOsType, pageNum: 0, pageSize: 1 }),
            ]);

            setStatsData({
                total: totalResult?.totalElements || 0,
                online: onlineResult?.totalElements || 0,
                offline: offlineResult?.totalElements || 0,
                unknown: unknownResult?.totalElements || 0,
            });
        } catch (error) {
            console.error('加载统计数据失败:', error);
        }
    };

    useEffect(() => {
        loadCategories();
        loadStats();
    }, [selectedCategoryId, selectedOsType]); // 移除 selectedStatus,因为统计不需要受状态筛选影响

    // 获取操作系统图标
    const getOsIcon = (osType?: string) => {
        const iconClass = "h-6 w-6";
        switch (osType) {
            case 'LINUX':
                return <Server className={iconClass} />;
            case 'WINDOWS':
                return <Monitor className={iconClass} />;
            case 'MACOS':
                return <Apple className={iconClass} />;
            case 'UNIX':
                return <Server className={iconClass} />;
            default:
                return <Server className={iconClass} />;
        }
    };

    // 加载服务器列表
    const loadServers = async (silent: boolean = false, isPagination: boolean = false) => {
        // silent 为 true 时不显示全局 loading 状态（用于操作后的静默刷新）
        // isPagination 为 true 时只显示分页 loading，不显示全局 loading
        if (!silent) {
            if (isPagination) {
                setPageLoading(true);
            } else {
                setLoading(true);
            }
        }
        try {
            const params = {
                categoryId: selectedCategoryId,
                status: selectedStatus,
                osType: selectedOsType,
            };
            
            // 卡片模式使用 list 接口（无分页），列表模式使用 page 接口（有分页）
            if (viewMode === 'grid') {
                // 卡片模式：调用 list 接口获取所有数据
                const result = await getServerList(params);
                if (result) {
                    setServers(result);
                    setTotalElements(result.length);
                }
            } else {
                // 列表模式：调用 page 接口获取分页数据
                const result = await getServers({
                    ...params,
                    pageNum: pageIndex,
                    pageSize: pageSize,
                });
                if (result) {
                    setServers(result.content || []);
                    setTotalElements(result.totalElements || 0);
                }
            }
        } catch (error) {
            console.error('加载服务器列表失败:', error);
            toast({
                variant: 'destructive',
                title: '加载失败',
                description: '无法加载服务器列表',
            });
        } finally {
            if (!silent) {
                setLoading(false);
                setPageLoading(false);
            }
        }
    };

    // 测试连接（轻量级）
    const handleTestConnection = async (server: ServerResponse) => {
        setTestingServerId(server.id);
        try {
            const result = await testServerConnection(server.id);
            if (result.connected) {
                toast({
                    title: '连接成功',
                    description: `响应时间: ${result.responseTime}ms`,
                });
                // 静默刷新服务器列表（不显示加载状态）
                await loadServers(true);
                await loadStats();
            } else {
                toast({
                    variant: 'destructive',
                    title: '连接失败',
                    description: result.errorMessage || '无法连接到服务器',
                });
            }
        } catch (error: any) {
            toast({
                variant: 'destructive',
                title: '测试失败',
                description: error.response?.data?.message || '无法连接到服务器',
            });
        } finally {
            setTestingServerId(null);
        }
    };

    // 刷新硬件信息
    const handleCollectHardware = async (server: ServerResponse) => {
        setCollectingServerId(server.id);
        
        // 显示开始采集的提示
        toast({
            title: '正在采集硬件信息...',
            description: `正在从 ${server.serverName} 采集最新硬件信息`,
        });
        
        try {
            const result = await collectServerHardware(server.id);
            
            // 静默刷新服务器列表（不显示加载状态）
            await loadServers(true);
            await loadStats();
            
            // 显示详细的成功信息
            toast({
                title: '✓ 硬件信息更新成功',
                description: (
                    <div className="space-y-1">
                        <div><strong>{result.hostname}</strong></div>
                        <div className="text-xs space-y-0.5">
                            <div>• CPU: {result.cpuCores} 核</div>
                            <div>• 内存: {result.memorySize} GB</div>
                            <div>• 磁盘: {result.diskSize} GB</div>
                        </div>
                    </div>
                ),
            });
        } catch (error: any) {
            toast({
                variant: 'destructive',
                title: '采集失败',
                description: error.response?.data?.message || '无法采集硬件信息，请检查服务器连接',
            });
        } finally {
            setCollectingServerId(null);
        }
    };

    // 编辑服务器
    const handleEdit = (server: ServerResponse) => {
        setEditingServer(server);
        setEditDialogOpen(true);
    };

    // 删除服务器
    const handleDelete = (server: ServerResponse) => {
        setServerToDelete(server);
        setDeleteDialogOpen(true);
    };

    // 监控数据
    const handleMonitor = (server: ServerResponse) => {
        setMonitoringServer(server);
        setMonitorDialogOpen(true);
    };

    // SSH连接 - 使用多窗口系统
    const handleSSHConnect = (server: ServerResponse) => {
        // 调用全局方法打开新的SSH窗口
        if ((window as any).__openSSHWindow) {
            (window as any).__openSSHWindow(server);
        } else {
            toast({
                title: "系统错误",
                description: "SSH窗口管理器未初始化",
                variant: "destructive",
            });
        }
    };

    const confirmDelete = async () => {
        if (!serverToDelete) return;
        await deleteServer(serverToDelete.id);
    };

    // 成功回调（新增/编辑服务器后）
    const handleSuccess = () => {
        loadCategories();
        loadServers(true); // 静默刷新
        loadStats();
    };

    // 页面变化
    const handlePageChange = (newPageIndex: number) => {
        setPageIndex(newPageIndex);
    };

    // 搜索按钮 - 应用筛选条件
    const handleSearch = () => {
        setSelectedCategoryId(tempCategoryId);
        setSelectedStatus(tempStatus);
        setSelectedOsType(tempOsType);
        setPageIndex(0); // 重置到第一页
    };

    // 重置按钮 - 清空所有筛选条件
    const handleReset = () => {
        setTempCategoryId(undefined);
        setTempStatus(undefined);
        setTempOsType(undefined);
        setSelectedCategoryId(undefined);
        setSelectedStatus(undefined);
        setSelectedOsType(undefined);
        setSearchKeyword('');
        setPageIndex(0); // 重置到第一页
    };

    // 客户端搜索过滤（在加载数据后进行）
    const filteredServers = servers.filter(server => {
        if (!searchKeyword.trim()) return true;
        const keyword = searchKeyword.toLowerCase();
        return (
            server.serverName.toLowerCase().includes(keyword) ||
            server.hostIp.includes(keyword) ||
            (server.hostname && server.hostname.toLowerCase().includes(keyword))
        );
    });

    // 监听筛选条件和视图模式变化（使用全局loading）
    useEffect(() => {
        loadServers(false, false); // 筛选加载，使用全局loading
    }, [pageSize, selectedCategoryId, selectedStatus, selectedOsType, viewMode]);

    // 监听分页变化（单独处理，使用pageLoading）
    useEffect(() => {
        if (viewMode === 'table') {
            // 表格模式下，分页变化时加载数据
            loadServers(false, true);
        }
    }, [pageIndex]);

    // 使用statsData作为统计数据
    const stats = statsData;

    return (
        <TooltipProvider>
            <div className="h-screen flex flex-col">
                {/* 顶部区域 - 统计和标题 */}
                <div className="flex-shrink-0 space-y-4 p-6">
                    {/* 标题栏 */}
                    <div>
                        <h1 className="text-3xl font-bold">服务器管理</h1>
                        <p className="text-muted-foreground mt-1">管理和监控服务器资源，支持SSH连接和分类管理</p>
                    </div>

                    {/* 统计卡片 - 更紧凑的布局 */}
                    <div className="grid gap-3 md:grid-cols-4">
                        <Card className="bg-gradient-to-br from-blue-50 to-indigo-50 dark:from-blue-950/20 dark:to-indigo-950/20 border-blue-200 dark:border-blue-900">
                            <CardContent className="p-4">
                                <div className="flex items-center justify-between">
                                    <div>
                                        <p className="text-xs text-muted-foreground font-medium">总服务器</p>
                                        <p className="text-2xl font-bold text-blue-600 dark:text-blue-400 mt-1">{stats.total}</p>
                                    </div>
                                    <Server className="h-8 w-8 text-blue-600 dark:text-blue-400 opacity-50" />
                                </div>
                            </CardContent>
                        </Card>
                        <Card className="bg-gradient-to-br from-green-50 to-emerald-50 dark:from-green-950/20 dark:to-emerald-950/20 border-green-200 dark:border-green-900">
                            <CardContent className="p-4">
                                <div className="flex items-center justify-between">
                                    <div>
                                        <p className="text-xs text-muted-foreground font-medium">在线</p>
                                        <p className="text-2xl font-bold text-green-600 dark:text-green-400 mt-1">{stats.online}</p>
                                    </div>
                                    <Activity className="h-8 w-8 text-green-600 dark:text-green-400 opacity-50" />
                                </div>
                            </CardContent>
                        </Card>
                        <Card className="bg-gradient-to-br from-red-50 to-rose-50 dark:from-red-950/20 dark:to-rose-950/20 border-red-200 dark:border-red-900">
                            <CardContent className="p-4">
                                <div className="flex items-center justify-between">
                                    <div>
                                        <p className="text-xs text-muted-foreground font-medium">离线</p>
                                        <p className="text-2xl font-bold text-red-600 dark:text-red-400 mt-1">{stats.offline}</p>
                                    </div>
                                    <AlertCircle className="h-8 w-8 text-red-600 dark:text-red-400 opacity-50" />
                                </div>
                            </CardContent>
                        </Card>
                        <Card className="bg-gradient-to-br from-gray-50 to-slate-50 dark:from-gray-950/20 dark:to-slate-950/20 border-gray-200 dark:border-gray-800">
                            <CardContent className="p-4">
                                <div className="flex items-center justify-between">
                                    <div>
                                        <p className="text-xs text-muted-foreground font-medium">未知</p>
                                        <p className="text-2xl font-bold text-gray-600 dark:text-gray-400 mt-1">{stats.unknown}</p>
                                    </div>
                                    <HelpCircle className="h-8 w-8 text-gray-600 dark:text-gray-400 opacity-50" />
                                </div>
                            </CardContent>
                        </Card>
                    </div>
                </div>

                {/* 内容区域 - 可滚动 */}
                <div className="flex-1 px-6 pb-6">
                    <Card className="h-full flex flex-col">
                        {/* 搜索和视图切换栏 */}
                        <CardHeader className="flex-shrink-0">
                            <div className="space-y-4">
                                {/* 搜索框 */}
                                <div className="flex items-center gap-2">
                                    <div className="flex-1">
                                        <Input
                                            placeholder="搜索服务器名称、IP或主机名..."
                                            value={searchKeyword}
                                            onChange={(e) => setSearchKeyword(e.target.value)}
                                            className="h-10"
                                        />
                                    </div>
                                    <div className="flex items-center gap-1 bg-muted/50 rounded-lg p-1">
                                        <Button
                                            variant={viewMode === 'grid' ? 'default' : 'ghost'}
                                            size="sm"
                                            onClick={() => setViewMode('grid')}
                                            className="h-8 px-3"
                                        >
                                            <Grid3x3 className="h-4 w-4" />
                                        </Button>
                                        <Button
                                            variant={viewMode === 'table' ? 'default' : 'ghost'}
                                            size="sm"
                                            onClick={() => setViewMode('table')}
                                            className="h-8 px-3"
                                        >
                                            <List className="h-4 w-4" />
                                        </Button>
                                    </div>
                                </div>

                                {/* 筛选栏 */}
                                <div className="flex items-center gap-3 p-4 bg-muted/30 rounded-lg flex-wrap">
                                    <div className="flex items-center gap-2">
                                        <Filter className="h-4 w-4 text-muted-foreground" />
                                        <span className="text-sm font-medium">筛选：</span>
                                    </div>

                                    <Select
                                        value={tempCategoryId?.toString() || 'all'}
                                        onValueChange={(value) => {
                                            setTempCategoryId(value === 'all' ? undefined : Number(value));
                                        }}
                                    >
                                        <SelectTrigger className="w-[180px]">
                                            <SelectValue placeholder="全部分类" />
                                        </SelectTrigger>
                                        <SelectContent>
                                            <SelectItem value="all">全部分类</SelectItem>
                                            {categories.map((cat) => (
                                                <SelectItem key={cat.id} value={cat.id.toString()}>
                                                    {cat.name}
                                                </SelectItem>
                                            ))}
                                        </SelectContent>
                                    </Select>

                                    <Select
                                        value={tempStatus || 'all'}
                                        onValueChange={(value) => {
                                            setTempStatus(value === 'all' ? undefined : (value as ServerStatus));
                                        }}
                                    >
                                        <SelectTrigger className="w-[140px]">
                                            <SelectValue placeholder="全部状态" />
                                        </SelectTrigger>
                                        <SelectContent>
                                            <SelectItem value="all">全部状态</SelectItem>
                                            {Object.entries(ServerStatusLabels).map(([key, value]) => (
                                                <SelectItem key={key} value={key}>
                                                    {value.label}
                                                </SelectItem>
                                            ))}
                                        </SelectContent>
                                    </Select>

                                    <Select
                                        value={tempOsType || 'all'}
                                        onValueChange={(value) => {
                                            setTempOsType(value === 'all' ? undefined : (value as OsType));
                                        }}
                                    >
                                        <SelectTrigger className="w-[140px]">
                                            <SelectValue placeholder="全部系统" />
                                        </SelectTrigger>
                                        <SelectContent>
                                            <SelectItem value="all">全部系统</SelectItem>
                                            {Object.entries(OsTypeLabels).map(([key, value]) => (
                                                <SelectItem key={key} value={key}>
                                                    {value.label}
                                                </SelectItem>
                                            ))}
                                        </SelectContent>
                                    </Select>

                                    <div className="flex gap-2 ml-auto">
                                        <Button
                                            variant="outline"
                                            size="sm"
                                            onClick={handleReset}
                                        >
                                            <RotateCcw className="h-4 w-4 mr-1.5" />
                                            重置
                                        </Button>
                                        <Button
                                            size="sm"
                                            onClick={handleSearch}
                                        >
                                            <Search className="h-4 w-4 mr-1.5" />
                                            查询
                                        </Button>
                                        <Button variant="outline" onClick={() => setAlertRuleDialogOpen(true)}>
                                            <Bell className="h-4 w-4 mr-2" />
                                            告警规则
                                        </Button>
                                        <Button variant="outline" onClick={() => setCategoryDialogOpen(true)}>
                                            <Settings className="h-4 w-4 mr-2" />
                                            分类管理
                                        </Button>
                                        <Button
                                            onClick={() => {
                                                setEditingServer(null);
                                                setEditDialogOpen(true);
                                            }}
                                        >
                                            <Plus className="h-4 w-4 mr-2" />
                                            新增服务器
                                        </Button>
                                    </div>
                                </div>
                            </div>
                        </CardHeader>

                        <Separator className="flex-shrink-0" />

                        {/* 内容区域 */}
                        <ScrollArea className="flex-1">
                            <CardContent className="pt-6">
                                <div className="space-y-4">
                                    {/* 加载状态 - 骨架屏 */}
                                    {loading && servers.length === 0 && (
                                        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
                                            {Array.from({ length: 8 }).map((_, index) => (
                                                <Card key={index} className="overflow-hidden">
                                                    <CardContent className="p-6 space-y-4">
                                                        <div className="flex items-start gap-4">
                                                            <Skeleton className="h-14 w-14 rounded-lg" />
                                                            <div className="flex-1 space-y-2">
                                                                <Skeleton className="h-5 w-32" />
                                                                <Skeleton className="h-4 w-24" />
                                                            </div>
                                                        </div>
                                                        <div className="space-y-3">
                                                            <Skeleton className="h-4 w-full" />
                                                            <Skeleton className="h-4 w-3/4" />
                                                            <Skeleton className="h-4 w-1/2" />
                                                        </div>
                                                        <div className="pt-4 border-t">
                                                            <Skeleton className="h-9 w-full" />
                                                        </div>
                                                    </CardContent>
                                                </Card>
                                            ))}
                                        </div>
                                    )}

                                    {/* 空状态 */}
                                    {!loading && filteredServers.length === 0 && (
                                        <div className="flex flex-col items-center justify-center py-24 text-muted-foreground">
                                            <Server className="h-16 w-16 mb-4 opacity-20" />
                                            <p className="text-lg font-medium">暂无服务器</p>
                                            <p className="text-sm mt-2">
                                                {servers.length === 0 ? '点击上方"新增服务器"按钮添加服务器' : '没有匹配搜索条件的服务器'}
                                            </p>
                                        </div>
                                    )}

                                    {/* 网格视图 */}
                                    {!loading && filteredServers.length > 0 && viewMode === 'grid' && (
                                        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
                                            {filteredServers.map((server) => (
                                                <ServerCard
                                                    key={server.id}
                                                    server={server}
                                                    onTest={handleTestConnection}
                                                    onEdit={handleEdit}
                                                    onDelete={handleDelete}
                                                    onSSHConnect={handleSSHConnect}
                                                    onCollectHardware={handleCollectHardware}
                                                    onMonitor={handleMonitor}
                                                    isTesting={testingServerId === server.id}
                                                    isCollecting={collectingServerId === server.id}
                                                    getOsIcon={getOsIcon}
                                                />
                                            ))}
                                        </div>
                                    )}

                                    {/* 表格视图 */}
                                    {!loading && filteredServers.length > 0 && viewMode === 'table' && (
                                        <div className="relative">
                                            {pageLoading && (
                                                <div className="absolute inset-0 bg-background/80 backdrop-blur-sm z-10 flex items-center justify-center">
                                                    <div className="flex items-center gap-2 text-sm text-muted-foreground">
                                                        <div className="h-4 w-4 animate-spin rounded-full border-2 border-primary border-t-transparent" />
                                                        <span>加载中...</span>
                                                    </div>
                                                </div>
                                            )}
                                            <ServerTable
                                                servers={filteredServers}
                                                loading={loading}
                                                onTest={handleTestConnection}
                                                onEdit={handleEdit}
                                                onDelete={handleDelete}
                                                onSSHConnect={handleSSHConnect}
                                                onCollectHardware={handleCollectHardware}
                                                onMonitor={handleMonitor}
                                                isTesting={(serverId) => testingServerId === serverId}
                                                isCollecting={(serverId) => collectingServerId === serverId}
                                                getOsIcon={getOsIcon}
                                            />
                                        </div>
                                    )}

                                    {/* 分页（仅列表模式） */}
                                    {!loading && servers.length > 0 && viewMode === 'table' && (
                                        <div className="mt-6 flex items-center justify-between">
                                            <div className="text-sm text-muted-foreground">
                                                共 {totalElements} 条记录，第 {pageIndex + 1} / {Math.ceil(totalElements / pageSize)} 页
                                                {searchKeyword && filteredServers.length > 0 && (
                                                    <span>，搜索结果 {filteredServers.length} 条</span>
                                                )}
                                            </div>
                                            <DataTablePagination
                                                pageIndex={pageIndex}
                                                pageSize={pageSize}
                                                pageCount={Math.ceil(totalElements / pageSize)}
                                                onPageChange={handlePageChange}
                                            />
                                        </div>
                                    )}
                                    
                                    {/* 卡片模式统计信息 */}
                                    {!loading && servers.length > 0 && viewMode === 'grid' && (
                                        <div className="mt-6 text-sm text-muted-foreground text-center">
                                            共 {totalElements} 台服务器
                                            {searchKeyword && filteredServers.length > 0 && (
                                                <span>，搜索结果 {filteredServers.length} 条</span>
                                            )}
                                        </div>
                                    )}
                                </div>
                            </CardContent>
                        </ScrollArea>
                    </Card>
                </div>
            </div>

            {/* 分类管理对话框 */}
            <CategoryManageDialog
                open={categoryDialogOpen}
                onOpenChange={setCategoryDialogOpen}
                onSuccess={handleSuccess}
            />

            {/* 告警规则管理对话框 */}
            <AlertRuleManageDialog
                open={alertRuleDialogOpen}
                onOpenChange={setAlertRuleDialogOpen}
                onSuccess={handleSuccess}
            />

            {/* 服务器编辑对话框 */}
            <ServerEditDialog
                open={editDialogOpen}
                onOpenChange={setEditDialogOpen}
                server={editingServer}
                onSuccess={handleSuccess}
            />

            {/* 删除确认对话框 */}
            <ConfirmDialog
                open={deleteDialogOpen}
                onOpenChange={setDeleteDialogOpen}
                title="确认删除"
                description={`确定要删除服务器"${serverToDelete?.serverName}"吗？此操作无法撤销。`}
                item={serverToDelete}
                onConfirm={confirmDelete}
                onSuccess={() => {
                    toast({
                        title: '删除成功',
                        description: `服务器"${serverToDelete?.serverName}"已删除`,
                    });
                    setServerToDelete(null);
                    loadServers(true); // 静默刷新
                    loadStats();
                }}
                variant="destructive"
                confirmText="确定"
            />

            {/* 监控数据对话框 */}
            <ServerMonitorDialog
                open={monitorDialogOpen}
                onOpenChange={setMonitorDialogOpen}
                server={monitoringServer}
            />

            {/* SSH多窗口管理器 */}
            <SSHWindowManager />
            
            {/* 文件管理器窗口管理器 */}
            <FileManagerWindowManager />
        </TooltipProvider>
    );
};

export default ServerList;

