'use client'

/**
 * HostGrid - 主機完整服務 Grid
 * ================================
 * 每張卡顯示：hostname + IP + CPU/RAM + 完整服務列表
 * K3s 主機: 藍色標記、K3s 徽章、獨立 Cluster 區塊
 * 專案鐵律：無數據顯示 "--"，禁止假數據
 *
 * @updated 2026-04-03 Claude Code — 完整服務清單 + K3s Cluster 突顯
 */

export interface HostService {
  name: string
  healthy: boolean
  port?: number
  description?: string
  isK3s?: boolean
}

export interface HostInfo {
  hostname: string
  ip: string
  cpuPct: number | null
  ramPct: number | null
  services: HostService[]
  isK3s?: boolean
  role?: string
}

export interface HostGridProps {
  hosts: HostInfo[]
}

function MetricBar({ value, warn = 80, critical = 90 }: { value: number | null; warn?: number; critical?: number }) {
  if (value === null) return <span style={{ color: '#b0ad9f', fontSize: 11 }}>--</span>
  const color = value >= critical ? '#cc2200' : value >= warn ? '#F59E0B' : '#22C55E'
  return <span style={{ color, fontSize: 11, fontWeight: 600 }}>{value}%</span>
}

function ServiceRow({ svc }: { svc: HostService }) {
  const isK3s = svc.isK3s ?? false
  const dotColor = isK3s ? '#4f8ef7' : svc.healthy ? '#22C55E' : '#b0ad9f'
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 5, minHeight: 16 }}>
      <div style={{ width: 4, height: 4, borderRadius: '50%', background: dotColor, flexShrink: 0 }} />
      <span style={{
        fontSize: 11,
        fontWeight: isK3s ? 600 : 400,
        color: isK3s ? '#3b7de8' : '#49483f',
        fontFamily: 'var(--font-body), monospace',
      }}>
        {svc.name}
      </span>
    </div>
  )
}

function HostCard({ host }: { host: HostInfo }) {
  const isK3s = host.isK3s ?? false
  const borderColor = isK3s ? '#93c5fd' : '#e0ddd4'
  const headerBg = isK3s ? '#eff6ff' : '#f5f4ed'
  const accentColor = isK3s ? '#3b7de8' : '#d97757'

  return (
    <div
      style={{
        border: `0.5px solid ${borderColor}`,
        borderRadius: 8,
        overflow: 'hidden',
        background: '#fff',
        transition: 'border-color 0.15s',
      }}
      onMouseEnter={e => { (e.currentTarget as HTMLDivElement).style.borderColor = accentColor }}
      onMouseLeave={e => { (e.currentTarget as HTMLDivElement).style.borderColor = borderColor }}
    >
      {/* Header */}
      <div style={{ background: headerBg, borderBottom: `0.5px solid ${borderColor}`, padding: '6px 9px' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 5 }}>
            <div style={{ width: 6, height: 6, borderRadius: '50%', background: accentColor, flexShrink: 0 }} />
            <span style={{ fontSize: 12, fontWeight: 700, color: '#141413', fontFamily: 'var(--font-body), monospace' }}>
              {/* 顯示末段 IP 作為簡短標識，完整名稱放 IP 欄位 */}
              {host.ip.includes('.') ? host.ip.split('.').pop() ?? host.ip : host.hostname}
            </span>
            {isK3s && (
              <span style={{
                fontSize: 9, fontWeight: 700, color: '#1d4ed8',
                background: '#dbeafe', borderRadius: 3, padding: '1px 4px', letterSpacing: '0.03em',
              }}>
                K3s
              </span>
            )}
          </div>
            <span style={{ fontSize: 10, color: '#b0ad9f', fontFamily: 'monospace' }}>{host.ip}</span>
          </div>
        <div style={{ display: 'flex', gap: 10, marginTop: 2 }}>
          <span style={{ fontSize: 10, color: '#b0ad9f' }}>CPU <MetricBar value={host.cpuPct} /></span>
          <span style={{ fontSize: 10, color: '#b0ad9f' }}>RAM <MetricBar value={host.ramPct} /></span>
          {host.role && (
            <span style={{ fontSize: 10, color: '#4f8ef7', marginLeft: 'auto' }}>{host.role}</span>
          )}
        </div>
      </div>

      {/* Services */}
      <div style={{ padding: '5px 9px 7px' }}>
        {host.services.length === 0 ? (
          <span style={{ fontSize: 11, color: '#b0ad9f' }}>--</span>
        ) : (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 1 }}>
            {host.services.map((svc, i) => <ServiceRow key={i} svc={svc} />)}
          </div>
        )}
      </div>
    </div>
  )
}

const K8S_VIP_INFO_FALLBACK =
  'K8S VIP topology (ops-only) · kubectl:6443 · web:32335 · api:32334'

export function HostGrid({ hosts }: HostGridProps) {
  if (hosts.length === 0) {
    return <div style={{ padding: 16, textAlign: 'center', color: '#b0ad9f', fontSize: 12 }}>--</div>
  }

  const normalHosts = hosts.filter(h => !h.isK3s)
  const k3sHosts = hosts.filter(h => h.isK3s)

  return (
    <div style={{ padding: '0 10px 10px', display: 'flex', flexDirection: 'column', gap: 6 }}>
      {/* Normal hosts — 2-col grid */}
      {normalHosts.length > 0 && (
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 6 }}>
          {normalHosts.map((host, i) => <HostCard key={i} host={host} />)}
        </div>
      )}

      {/* K3s Cluster — full-width highlighted block */}
      {k3sHosts.length > 0 && (
        <div style={{ border: '1px solid #93c5fd', borderRadius: 8, overflow: 'hidden', background: '#f8fbff' }}>
          {/* Cluster banner */}
          <div style={{
            background: '#dbeafe',
            borderBottom: '0.5px solid #93c5fd',
            padding: '4px 10px',
            display: 'flex',
            alignItems: 'center',
            gap: 8,
          }}>
            <span style={{ fontSize: 10, fontWeight: 800, color: '#1d4ed8', letterSpacing: '0.08em' }}>
              ☸ K3S CLUSTER (HA)
            </span>
            <span style={{ fontSize: 10, color: '#3b7de8' }}>
              {(process.env.NEXT_PUBLIC_K8S_VIP_INFO ?? '').trim() || K8S_VIP_INFO_FALLBACK}
            </span>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 6, padding: 6 }}>
            {k3sHosts.map((host, i) => <HostCard key={i} host={host} />)}
          </div>
        </div>
      )}
    </div>
  )
}

export default HostGrid
