import { useApi } from '../hooks/useApi'
import { guardiaApi } from '../api/clients'
import { DataTable } from '../components/common/DataTable'
import { StatusBadge } from '../components/common/StatusBadge'
import type { Server } from '../api/types'

export default function CMDB() {
  const { data, loading } = useApi<{ items: Server[]; total: number }>(guardiaApi, '/api/cmdb/servers?limit=100')
  const servers = data?.items ?? []

  const byStatus = servers.reduce((acc, s) => {
    acc[s.status ?? 'unknown'] = (acc[s.status ?? 'unknown'] ?? 0) + 1; return acc
  }, {} as Record<string, number>)

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
      {/* 요약 카드 */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12 }}>
        {[
          { label: '전체', count: servers.length, color: '#e8ecff' },
          { label: '실행중', count: byStatus['running'] ?? 0, color: '#dcfce7' },
          { label: '중지', count: byStatus['stopped'] ?? 0, color: '#f5f5f5' },
          { label: '오류', count: byStatus['error'] ?? 0, color: '#fee2e2' },
        ].map(c => (
          <div key={c.label} style={{ border: '1px solid #e2e8f0',
            borderRadius: 10, padding: '16px 20px', background: c.color }}>
            <div style={{ fontSize: 22, fontWeight: 700 }}>{c.count}</div>
            <div style={{ fontSize: 12, color: '#64748b' }}>{c.label}</div>
          </div>
        ))}
      </div>

      <DataTable<Server>
        cols={[
          { key: 'id',        header: 'ID',     width: 60 },
          { key: 'hostname',  header: '호스트명' },
          { key: 'os_type',   header: 'OS' },
          { key: 'inst_name', header: '기관' },
          { key: 'status',    header: '상태', render: r => <StatusBadge status={r.status ?? 'unknown'} /> },
        ]}
        rows={servers}
        loading={loading}
        empty="CMDB 서버 데이터가 없습니다."
        toolbar={<span style={{ fontSize: 12, color: '#64748b' }}>CMDB 서버 자산 — 총 {servers.length}대</span>}
      />
    </div>
  )
}
