import type { ServerConfig, ServerMetrics } from '../../types';
import { formatUptime, formatBytes } from '../../utils/format';
import { useSortable } from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';
import './ServerCard.css';

const CircularProgress = ({ value, label, color, size = 60 }: { value: number; label: string; color: string; size?: number }) => {
  const radius = size * 0.36;
  const circumference = 2 * Math.PI * radius;
  const offset = circumference - (value / 100) * circumference;
  
  return (
    <div className="circular-progress-small">
      <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`}>
        <circle
          className="progress-ring-bg"
          cx={size / 2}
          cy={size / 2}
          r={radius}
        />
        <circle
          className="progress-ring-circle"
          stroke={color}
          strokeDasharray={`${circumference} ${circumference}`}
          strokeDashoffset={offset}
          cx={size / 2}
          cy={size / 2}
          r={radius}
        />
        <text x={size / 2} y={size / 2 - 8} className="progress-value-small" textAnchor="middle" dy="7px">
          {Math.round(value)}%
        </text>
        <text x={size / 2} y={size / 2 + 12} className="progress-label-small" textAnchor="middle">
          {label}
        </text>
      </svg>
    </div>
  );
};

const LoadProgress = ({ value, maxValue = 1.0, size = 80 }: { value: number; maxValue?: number; size?: number }) => {
  const percentage = Math.min((value / maxValue) * 100, 100);
  const radius = size * 0.36;
  const circumference = 2 * Math.PI * radius;
  const offset = circumference - (percentage / 100) * circumference;
  const color = percentage > 80 ? '#f87171' : percentage > 50 ? '#fde047' : '#86efac';
  
  return (
    <div className="circular-progress-small">
      <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`}>
        <circle
          className="progress-ring-bg"
          cx={size / 2}
          cy={size / 2}
          r={radius}
        />
        <circle
          className="progress-ring-circle"
          stroke={color}
          strokeDasharray={`${circumference} ${circumference}`}
          strokeDashoffset={offset}
          cx={size / 2}
          cy={size / 2}
          r={radius}
        />
        <text x={size / 2} y={size / 2 - 8} className="progress-value-small" textAnchor="middle" dy="7px">
          {value.toFixed(2)}
        </text>
        <text x={size / 2} y={size / 2 + 12} className="progress-label-small" textAnchor="middle">
          负载
        </text>
      </svg>
    </div>
  );
};

export interface ServerCardProps {
  server: ServerConfig;
  online: boolean;
  metrics?: ServerMetrics;
  cpuUsage?: number;
  memoryUsage?: number;
  storageUsage?: number;
  uptime?: number;
  onDetail: (serverId: string) => void;
  onRemove: (serverId: string) => void;
}

export const ServerCard = ({
  server,
  online,
  metrics,
  cpuUsage = 0,
  memoryUsage = 0,
  storageUsage = 0,
  uptime,
  onDetail,
  onRemove,
}: ServerCardProps) => {
  const {
    attributes,
    listeners,
    setNodeRef,
    transform,
    transition,
    isDragging,
  } = useSortable({ id: server.id });

  const style = {
    transform: CSS.Transform.toString(transform),
    transition,
    opacity: isDragging ? 0.5 : 1,
  };

  // 从 URL 提取 IP 地址
  const extractIP = (url: string): string => {
    try {
      const urlObj = new URL(url);
      return urlObj.hostname;
    } catch {
      return url;
    }
  };

  // 获取主 IP 地址（从网络接口）
  const getMainIP = (): string => {
    if (metrics?.network && metrics.network.length > 0) {
      const mainInterface = metrics.network.find(iface => 
        iface.ipAddress && iface.ipAddress !== 'N/A' && !iface.ipAddress.startsWith('127.')
      );
      return mainInterface?.ipAddress || extractIP(server.url);
    }
    return extractIP(server.url);
  };

  const mainIP = getMainIP();
  const loadAverage = metrics?.cpu?.loadAverages?.[0] || 0;
  const cpuCores = metrics?.cpu?.cores || 1;
  const temperature = metrics?.system?.temperature || metrics?.cpu?.temperature || 0;
  const hostname = metrics?.hostname || 'Unknown';
  const osDistro = metrics?.os?.distro || 'Unknown';
  const architecture = metrics?.os?.architecture || 'Unknown';
  const diskReadSpeed = metrics?.system?.diskReadSpeed || 0;
  const diskWriteSpeed = metrics?.system?.diskWriteSpeed || 0;
  const networkRxSpeed = metrics?.system?.networkRxSpeed || 0;
  const networkTxSpeed = metrics?.system?.networkTxSpeed || 0;
  const latency = metrics?.latency?.clientToServer || -1;
  const processCount = metrics?.system?.processCount || 0;
  const packageCount = metrics?.system?.packageCount || 0;

  // 延迟颜色判断
  const getLatencyColor = (latency: number): string => {
    if (latency < 0) return '#ef4444'; // 超时/失败 - 红色
    if (latency < 50) return '#86efac'; // 低延迟 - 绿色
    if (latency < 200) return '#fde047'; // 中延迟 - 黄色
    return '#f87171'; // 高延迟 - 红色
  };

  const latencyColor = getLatencyColor(latency);

  return (
    <div 
      ref={setNodeRef}
      style={style}
      className={`server-card ${online ? 'online' : 'offline'}`}
    >
      <div className="card-header" {...attributes} {...listeners}>
        <div className="server-info">
          <div className={`status-indicator ${online ? 'status-online' : 'status-offline'}`} />
          <div className="server-name-group">
            <h3 className="server-name">{server.name}</h3>
            {online && hostname !== 'Unknown' && (
              <span className="server-hostname">{hostname}</span>
            )}
          </div>
        </div>
        <button 
          className="btn-remove" 
          onPointerDown={(e) => e.stopPropagation()}
          onClick={(e) => {
            e.stopPropagation();
            onRemove(server.id);
          }} 
          title="移除服务器"
        >
          ×
        </button>
      </div>

      {online && metrics ? (
        <>
          <div className="card-main-metrics">
            <div className="metrics-grid-main">
              {loadAverage > 0 && (
                <LoadProgress value={loadAverage} maxValue={cpuCores} size={80} />
              )}
              <CircularProgress 
                value={cpuUsage} 
                label="CPU" 
                color={cpuUsage > 80 ? '#f87171' : '#86efac'} 
                size={80}
              />
              <CircularProgress 
                value={memoryUsage} 
                label="内存" 
                color={memoryUsage > 80 ? '#fde047' : '#6ee7b7'} 
                size={80}
              />
              <CircularProgress 
                value={storageUsage} 
                label="存储" 
                color={storageUsage > 90 ? '#f87171' : '#a7f3d0'} 
                size={80}
              />
            </div>

            <div className="card-info-grid">
              <div className="info-section">
                <div className="info-row">
                  <span className="info-label">系统</span>
                  <span className="info-value">{osDistro}</span>
                </div>
                <div className="info-row">
                  <span className="info-label">架构</span>
                  <span className="info-value">{architecture}</span>
                </div>
                <div className="info-row">
                  <span className="info-label">IP</span>
                  <span className="info-value">{mainIP}</span>
                </div>
              </div>

              <div className="info-section">
                <div className="info-row">
                  <span className="info-label">温度</span>
                  <span className="info-value">{temperature > 0 ? `${temperature.toFixed(1)}°C` : 'N/A'}</span>
                </div>
                <div className="info-row">
                  <span className="info-label">进程</span>
                  <span className="info-value">{processCount}</span>
                </div>
                <div className="info-row">
                  <span className="info-label">软件包</span>
                  <span className="info-value">{packageCount}</span>
                </div>
              </div>
            </div>

            <div className="card-performance-grid">
              <div className="performance-section">
                <div className="performance-header">
                  <span className="performance-label">磁盘</span>
                </div>
                <div className="performance-row">
                  <span className="performance-item">
                    <span className="performance-item-label">读取</span>
                    <span className="performance-item-value">{diskReadSpeed > 0 ? formatBytes(diskReadSpeed * 1024 * 1024) + '/s' : '0 B/s'}</span>
                  </span>
                  <span className="performance-item">
                    <span className="performance-item-label">写入</span>
                    <span className="performance-item-value">{diskWriteSpeed > 0 ? formatBytes(diskWriteSpeed * 1024 * 1024) + '/s' : '0 B/s'}</span>
                  </span>
                </div>
              </div>

              <div className="performance-section">
                <div className="performance-header">
                  <span className="performance-label">网络</span>
                </div>
                <div className="performance-row">
                  <span className="performance-item">
                    <span className="performance-item-label">下载</span>
                    <span className="performance-item-value">{networkRxSpeed > 0 ? formatBytes(networkRxSpeed * 1024 * 1024) + '/s' : '0 B/s'}</span>
                  </span>
                  <span className="performance-item">
                    <span className="performance-item-label">上传</span>
                    <span className="performance-item-value">{networkTxSpeed > 0 ? formatBytes(networkTxSpeed * 1024 * 1024) + '/s' : '0 B/s'}</span>
                  </span>
                </div>
              </div>
            </div>

            <div className="card-footer-info">
              <div className="footer-row">
                <span className="footer-label">运行时间</span>
                <span className="footer-value">{uptime !== undefined ? formatUptime(uptime) : 'N/A'}</span>
              </div>
              <div className="footer-row">
                <span className="footer-label">延迟</span>
                <span className="footer-value" style={{ color: latencyColor }}>
                  {latency > 0 ? `${latency} ms` : latency === -1 ? '超时' : 'N/A'}
                </span>
              </div>
            </div>
          </div>
        </>
      ) : (
        <div className="offline-state">
          <p>服务器连接断开</p>
        </div>
      )}
      
      <div className="card-footer">
        <button className="btn-detail" onClick={() => onDetail(server.id)}>
          查看详情
        </button>
      </div>
    </div>
  );
};
