import React from 'react';
import {
    Cpu,
    HardDrive,
    MemoryStick,
    Network,
    Clock,
    TestTube,
    Pencil,
    Trash2,
    Loader2,
    ChevronDown,
    Terminal,
    MonitorDot,
    Tags,
    Tag,
    FileText,
    RefreshCw,
    BarChart3,
} from 'lucide-react';
import { Card, CardContent } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
import { Skeleton } from '@/components/ui/skeleton';
import type { ServerResponse } from '../types';
import { ServerStatusLabels, OsTypeLabels } from '../types';
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';
import 'dayjs/locale/zh-cn';

dayjs.extend(relativeTime);
dayjs.locale('zh-cn');

interface ServerCardProps {
    server: ServerResponse;
    onTest: (server: ServerResponse) => void;
    onEdit: (server: ServerResponse) => void;
    onDelete: (server: ServerResponse) => void;
    onSSHConnect: (server: ServerResponse) => void;
    onCollectHardware: (server: ServerResponse) => void;
    onMonitor: (server: ServerResponse) => void;
    isTesting?: boolean;
    isCollecting?: boolean;
    getOsIcon: (osType?: string) => React.ReactNode;
}

export const ServerCard: React.FC<ServerCardProps> = ({ server, onTest, onEdit, onDelete, onSSHConnect, onCollectHardware, onMonitor, isTesting, isCollecting, getOsIcon }) => {
    const [expanded, setExpanded] = React.useState(false);

    const formatTime = (time?: string) => {
        if (!time) return '-';
        return dayjs(time).fromNow();
    };

    const renderValue = (
        content: React.ReactNode,
        skeletonWidth: string,
        options?: { skeleton?: boolean; skeletonHeight?: string; fallback?: React.ReactNode }
    ) => {
        if (content === undefined || content === null || content === '' || content === false) {
            if (options?.skeleton) {
                return (
                    <Skeleton
                        className={`${options.skeletonHeight ?? 'h-3'} rounded ${skeletonWidth}`}
                    />
                );
            }
            return options?.fallback ?? null;
        }
        return content;
    };

    return (
        <Card className={`group relative flex h-full flex-col justify-between overflow-visible border transition-all duration-200 hover:border-primary/40 hover:shadow-lg ${
            expanded ? 'rounded-b-none border-b-0' : ''
        }`}>
            {/* ID Badge - 悬浮在左上角，类似通知样式 */}
            <div className="absolute -left-2 -top-2 z-10 flex h-6 w-6 items-center justify-center rounded-full bg-primary text-[10px] font-bold text-primary-foreground shadow-md">
                {server.id}
            </div>
            
            <CardContent className="flex flex-1 flex-col gap-3 p-3">
                {/* 基础信息 */}
                <div className="flex items-start gap-3">
                    {/* 左侧：操作系统大图标 */}
                    <div className="flex h-14 w-14 flex-shrink-0 items-center justify-center rounded-lg bg-muted/50">
                        {server.osType ? (
                            <div className="h-8 w-8 text-primary">{getOsIcon(server.osType)}</div>
                        ) : (
                            <Skeleton className="h-8 w-8 rounded" />
                        )}
                    </div>
                    
                    {/* 主要内容区域 */}
                    <div className="flex min-w-0 flex-1 flex-col gap-1.5">
                        {/* 第一行：状态徽章 + 分类 */}
                        <div className="flex flex-wrap items-center gap-2">
                            <div
                                className={`h-2 w-2 rounded-full flex-shrink-0 ${
                                    server.status === 'ONLINE'
                                        ? 'bg-emerald-500 animate-pulse'
                                        : server.status === 'OFFLINE'
                                        ? 'bg-red-500'
                                        : 'bg-slate-400'
                                }`}
                            />
                            {renderValue(
                                <Badge
                                    variant="outline"
                                    className={`border-transparent text-[11px] font-medium ${
                                        server.status === 'ONLINE'
                                            ? 'bg-emerald-100 text-emerald-700 dark:bg-emerald-500/10 dark:text-emerald-300'
                                            : server.status === 'OFFLINE'
                                            ? 'bg-red-100 text-red-700 dark:bg-red-500/10 dark:text-red-300'
                                            : 'bg-slate-100 text-slate-700 dark:bg-slate-700/30 dark:text-slate-200'
                                    }`}
                                >
                                    {(server.status && ServerStatusLabels[server.status]?.label) || server.status}
                                </Badge>,
                                'w-16'
                            )}
                            {server.categoryName && (
                                <Badge variant="outline" className="text-[11px]">
                                    {server.categoryName}
                                </Badge>
                            )}
                        </div>
                        
                        {/* 服务器名图标：NAS（QC-NAS） */}
                        {renderValue(
                            <div className="flex items-center gap-1.5 text-sm">
                                <Tag className="h-3.5 w-3.5 flex-shrink-0 text-muted-foreground" />
                                <span className="font-semibold text-foreground truncate">
                                    {server.serverName}
                                    {server.hostname && (
                                        <span className="text-muted-foreground font-normal">（{server.hostname}）</span>
                                    )}
                                </span>
                            </div>,
                            'w-32',
                            { skeleton: true }
                        )}
                        
                        {/* IP图标：172.22.222.111 */}
                        <div className="flex items-center gap-1.5 text-xs">
                            <Network className="h-3.5 w-3.5 flex-shrink-0 text-muted-foreground" />
                            {renderValue(
                                <span className="font-mono text-foreground">{server.hostIp}</span>,
                                'w-24',
                                { skeleton: true }
                            )}
                        </div>
                        
                        {/* 操作系统版本图标：Linux Debian... */}
                        <div className="flex items-center gap-1.5 text-xs">
                            <MonitorDot className="h-3.5 w-3.5 flex-shrink-0 text-muted-foreground" />
                            {renderValue(
                                server.osType ? (
                                    <span className="text-muted-foreground truncate">
                                        {OsTypeLabels[server.osType]?.label || server.osType}
                                        {server.osVersion && ` ${server.osVersion}`}
                                    </span>
                                ) : null,
                                'w-40',
                                { skeleton: true }
                            )}
                        </div>
                        
                        {/* 标签图标：华为云 阿里云 */}
                        <div className="flex items-center gap-1.5">
                            <Tags className="h-3.5 w-3.5 flex-shrink-0 text-muted-foreground" />
                            {renderValue(
                                (() => {
                                    try {
                                        const tags = server.tags ? JSON.parse(server.tags) : [];
                                        if (Array.isArray(tags) && tags.length > 0) {
                                            return (
                                                <div className="flex flex-wrap gap-1">
                                                    {tags.slice(0, 3).map((tag: string, index: number) => (
                                                        <Badge key={index} variant="outline" className="text-[10px] py-0 px-1.5">
                                                            {tag}
                                                        </Badge>
                                                    ))}
                                                    {tags.length > 3 && (
                                                        <Badge variant="outline" className="text-[10px] py-0 px-1.5">
                                                            +{tags.length - 3}
                                                        </Badge>
                                                    )}
                                                </div>
                                            );
                                        }
                                        return null;
                                    } catch {
                                        return null;
                                    }
                                })(),
                                'w-32',
                                { skeleton: true }
                            )}
                        </div>
                        
                        {/* 描述图标：测试 */}
                        <div className="flex items-start gap-1.5">
                            <FileText className="h-3.5 w-3.5 flex-shrink-0 text-muted-foreground mt-0.5" />
                            {renderValue(
                                server.description ? (
                                    <p className="text-[11px] text-muted-foreground line-clamp-2 flex-1">
                                        {server.description}
                                    </p>
                                ) : null,
                                'w-full',
                                { skeleton: true }
                            )}
                        </div>
                    </div>
                    
                    {/* 右侧：展开按钮 */}
                    <Button
                        type="button"
                        variant="ghost"
                        size="icon"
                        className={`h-7 w-7 flex-shrink-0 rounded-full border border-border/50 transition-transform ${
                            expanded ? 'rotate-180' : ''
                        }`}
                        onClick={() => setExpanded((prev) => !prev)}
                    >
                        <ChevronDown className="h-4 w-4" />
                    </Button>
                </div>

                {/* 快速信息 */}
                <div className="flex items-center justify-between text-[11px] text-muted-foreground">
                    <div className="flex items-center gap-2">
                        <Clock className="h-3 w-3" />
                        {server.lastConnectTime ? (
                            <span>最后连接 {formatTime(server.lastConnectTime)}</span>
                        ) : (
                            <span className="text-muted-foreground/50">暂无连接记录</span>
                        )}
                    </div>
                    <div className="flex items-center gap-1.5">
                        <Tooltip>
                            <TooltipTrigger asChild>
                                <Button
                                    type="button"
                                    variant="ghost"
                                    size="icon"
                                    className="h-7 w-7 text-primary"
                                    onClick={() => onMonitor(server)}
                                >
                                    <BarChart3 className="h-3.5 w-3.5" />
                                </Button>
                            </TooltipTrigger>
                            <TooltipContent>监控数据</TooltipContent>
                        </Tooltip>
                        <Tooltip>
                            <TooltipTrigger asChild>
                                <Button
                                    type="button"
                                    variant="ghost"
                                    size="icon"
                                    className="h-7 w-7 text-primary"
                                    onClick={() => onSSHConnect(server)}
                                >
                                    <Terminal className="h-3.5 w-3.5" />
                                </Button>
                            </TooltipTrigger>
                            <TooltipContent>SSH连接</TooltipContent>
                        </Tooltip>
                        <Tooltip>
                            <TooltipTrigger asChild>
                                <Button
                                    type="button"
                                    variant="ghost"
                                    size="icon"
                                    className="h-7 w-7"
                                    onClick={() => onTest(server)}
                                    disabled={isTesting || isCollecting}
                                >
                                    {isTesting ? (
                                        <Loader2 className="h-3.5 w-3.5 animate-spin" />
                                    ) : (
                                        <TestTube className="h-3.5 w-3.5" />
                                    )}
                                </Button>
                            </TooltipTrigger>
                            <TooltipContent>测试连接</TooltipContent>
                        </Tooltip>
                        <Tooltip>
                            <TooltipTrigger asChild>
                                <Button
                                    type="button"
                                    variant="ghost"
                                    size="icon"
                                    className="h-7 w-7"
                                    onClick={() => onCollectHardware(server)}
                                    disabled={isTesting || isCollecting}
                                >
                                    {isCollecting ? (
                                        <Loader2 className="h-3.5 w-3.5 animate-spin" />
                                    ) : (
                                        <RefreshCw className="h-3.5 w-3.5" />
                                    )}
                                </Button>
                            </TooltipTrigger>
                            <TooltipContent>刷新硬件信息</TooltipContent>
                        </Tooltip>
                        <Tooltip>
                            <TooltipTrigger asChild>
                                <Button
                                    type="button"
                                    variant="ghost"
                                    size="icon"
                                    className="h-7 w-7"
                                    onClick={() => onEdit(server)}
                                >
                                    <Pencil className="h-3.5 w-3.5" />
                                </Button>
                            </TooltipTrigger>
                            <TooltipContent>编辑</TooltipContent>
                        </Tooltip>
                        <Tooltip>
                            <TooltipTrigger asChild>
                                <Button
                                    type="button"
                                    variant="ghost"
                                    size="icon"
                                    className="h-7 w-7 text-destructive"
                                    onClick={() => onDelete(server)}
                                >
                                    <Trash2 className="h-3.5 w-3.5" />
                                </Button>
                            </TooltipTrigger>
                            <TooltipContent>删除</TooltipContent>
                        </Tooltip>
                    </div>
                </div>
            </CardContent>

            {/* 展开内容 - 仅显示SSH信息和大图标配置 */}
            {expanded && (
                <div className="absolute left-[-1px] right-[-1px] top-full z-20 space-y-3 rounded-b-xl border-x border-b border-border bg-card p-3 text-xs shadow-lg group-hover:border-primary/40">
                    {/* SSH连接信息 */}
                    <div className="flex flex-wrap items-center gap-2">
                        {renderValue(
                            <span className="text-muted-foreground">
                                SSH：
                                <span className="ml-1 font-medium text-foreground">
                                    {(server.sshUser || 'root') + ':' + (server.sshPort || 22)}
                                </span>
                            </span>,
                            'w-32'
                        )}
                        {server.authType && (
                            <Badge variant="secondary" className="text-[11px]">
                                {server.authType === 'PASSWORD' ? '密码认证' : '密钥认证'}
                            </Badge>
                        )}
                    </div>
                    
                    {/* 详细配置信息 - 大图标展示 */}
                    <div className="grid grid-cols-3 gap-2 text-center">
                        <div className="flex flex-col items-center gap-1">
                            <div className="flex h-10 w-10 items-center justify-center rounded-full bg-primary/10 text-primary">
                                <Cpu className="h-5 w-5" />
                            </div>
                            {renderValue(
                                server.cpuCores ? (
                                    <span className="text-xs font-medium text-foreground">{server.cpuCores}核</span>
                                ) : null,
                                'w-10',
                                { skeleton: true, skeletonHeight: 'h-4' }
                            )}
                        </div>
                        <div className="flex flex-col items-center gap-1">
                            <div className="flex h-10 w-10 items-center justify-center rounded-full bg-primary/10 text-primary">
                                <MemoryStick className="h-5 w-5" />
                            </div>
                            {renderValue(
                                server.memorySize ? (
                                    <span className="text-xs font-medium text-foreground">{server.memorySize}GB</span>
                                ) : null,
                                'w-10',
                                { skeleton: true, skeletonHeight: 'h-4' }
                            )}
                        </div>
                        <Tooltip>
                            <TooltipTrigger asChild>
                                <div className="flex flex-col items-center gap-1 cursor-help">
                                    <div className="flex h-10 w-10 items-center justify-center rounded-full bg-primary/10 text-primary">
                                        <HardDrive className="h-5 w-5" />
                                    </div>
                                    {renderValue(
                                        server.diskSize ? (
                                            <span className="text-xs font-medium text-foreground">{server.diskSize}GB</span>
                                        ) : null,
                                        'w-10',
                                        { skeleton: true, skeletonHeight: 'h-4' }
                                    )}
                                </div>
                            </TooltipTrigger>
                            {server.diskInfo && server.diskInfo.length > 0 && (
                                <TooltipContent className="max-w-xs">
                                    <div className="space-y-2">
                                        <div className="font-semibold text-xs border-b pb-1">磁盘详情</div>
                                        {server.diskInfo.map((disk, index) => (
                                            <div key={index} className="flex justify-between gap-4 text-xs">
                                                <div className="flex items-center gap-2">
                                                    <span className="font-mono text-blue-400">{disk.mountPoint}</span>
                                                    <span className="text-muted-foreground">({disk.fileSystem})</span>
                                                </div>
                                                <span className="font-medium">{disk.totalSize}GB</span>
                                            </div>
                                        ))}
                                        <div className="flex justify-between gap-4 text-xs font-semibold border-t pt-1">
                                            <span>总计</span>
                                            <span>{server.diskSize}GB</span>
                                        </div>
                                    </div>
                                </TooltipContent>
                            )}
                        </Tooltip>
                    </div>
                </div>
            )}
        </Card>
    );
};

