import type { ServerConfig, ServerMetrics } from '../../types';
import { formatUptime, formatBytes, formatPercent, formatLatencyMs } from '../../utils/format';
import './ServerCard.css';

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

export const ServerCard = ({
  server,
  online,
  metrics,
  cpuUsage = 0,
  memoryUsage = 0,
  storageUsage = 0,
  uptime,
  onDetail,
}: ServerCardProps) => {
  const extractIP = (url: string): string => {
    try {
      const urlObj = new URL(url);
      return urlObj.hostname;
    } catch {
      return url;
    }
  };

  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 loggedInUsers = metrics?.system?.loggedInUsers;
  const tcpConnections = metrics?.system?.tcpConnections;
  const swapTotalBytes = metrics?.memory?.swapTotalBytes;
  const swapType = metrics?.memory?.swapType;

  const loadRatio = cpuCores > 0 ? (loadAverage / cpuCores) * 100 : 0;

  const latencyClass =
    !Number.isFinite(latency) || latency < 0
      ? 'lat-bad'
      : latency < 50
        ? 'lat-good'
        : latency < 200
          ? 'lat-mid'
          : 'lat-bad';

  return (
    <div className={`server-card ${online ? 'online' : 'offline'}`}>
      <div className="card-header">
        <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>
      </div>

      {!online ? (
        <div className="offline-state">
          <p>服务器连接断开</p>
        </div>
      ) : !metrics ? (
        <div className="offline-state sync-pending">
          <p>正在从中心同步指标…</p>
        </div>
      ) : (
        <>
          <div className="card-main-metrics">
            <div className="card-stats-compact">
              {loadAverage > 0 && (
                <div className="stat-line">
                  <span className="stat-k">负载</span>
                  <span className="stat-v">
                    {loadAverage.toFixed(2)} / {cpuCores} 核（≈ {formatPercent(loadRatio)}）
                  </span>
                </div>
              )}
              <div className="stat-line">
                <span className="stat-k">CPU</span>
                <span className="stat-v">{formatPercent(cpuUsage)}</span>
              </div>
              <div className="stat-line">
                <span className="stat-k">内存</span>
                <span className="stat-v">{formatPercent(memoryUsage)}</span>
              </div>
              <div className="stat-line">
                <span className="stat-k">存储峰值</span>
                <span className="stat-v">{formatPercent(storageUsage)}</span>
              </div>
              {swapTotalBytes !== undefined && (
                <div className="stat-line">
                  <span className="stat-k">Swap</span>
                  <span className="stat-v">
                    {formatBytes(swapTotalBytes)}
                    {swapType ? ` · ${swapType}` : ''}
                  </span>
                </div>
              )}
              {tcpConnections !== undefined && (
                <div className="stat-line">
                  <span className="stat-k">TCP</span>
                  <span className="stat-v">{tcpConnections}</span>
                </div>
              )}
            </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>
                {loggedInUsers !== undefined && (
                  <div className="info-row">
                    <span className="info-label">会话</span>
                    <span className="info-value">{loggedInUsers}</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" title="采集器到监控中心的 TCP 建连耗时（由采集端上报）">
                <span className="footer-label">采集器→中心</span>
                <span className={`footer-value ${latencyClass}`}>{formatLatencyMs(latency)}</span>
              </div>
            </div>
          </div>
        </>
      )}

      <div className="card-footer">
        <button type="button" className="btn-detail" onClick={() => onDetail(server.id)}>
          查看详情
        </button>
      </div>
    </div>
  );
};
