import { Badge } from 'antd'
import React from 'react'

import { formatTime } from 'utils/time'

type BadgeStatus = React.ComponentProps<typeof Badge>['status']

// Explicit switch — unknown values render as raw text with the default
// status so new server states are immediately visible to operators.
export function statusBadgeStatus(status: string | undefined): BadgeStatus {
  switch ((status || '').toLowerCase()) {
    case 'running':
    case 'preparing':
    case 'pending':
    case 'processing':
    case 'creating':
    case 'starting':
    case 'stopping':
    case 'scaling':
    case 'editing':
    case 'deleting':
      return 'processing'
    case 'succeeded':
    case 'success':
    case 'passed':
    case 'finished':
    case 'normal':
    case 'enabled':
      return 'success'
    case 'paused':
    case 'warning':
    case 'stopped':
      return 'warning'
    case 'failed':
    case 'error':
    case 'canceled':
      return 'error'
    default:
      return 'default'
  }
}

export function statusBadge(status: string | undefined) {
  return React.createElement(Badge, {
    status: statusBadgeStatus(status),
    text: status || '—'
  })
}

export function formatTs(tsSec: number | undefined): string {
  return formatTime(tsSec ? tsSec * 1000 : undefined) ?? '—'
}

export function formatBytes(bytes: number | undefined): string {
  if (bytes === undefined || bytes === null) return '—'
  if (!Number.isFinite(bytes) || bytes < 0) return '—'
  if (bytes === 0) return '0 B'
  const units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']
  const i = Math.min(
    Math.floor(Math.log(bytes) / Math.log(1024)),
    units.length - 1
  )
  return (bytes / Math.pow(1024, i)).toFixed(i === 0 ? 0 : 2) + ' ' + units[i]
}

export function formatDuration(sec: number | undefined): string {
  if (sec === undefined || sec === null) return '—'
  if (!Number.isFinite(sec) || sec < 0) return '—'
  if (sec < 60) return sec + 's'
  if (sec < 3600) return Math.floor(sec / 60) + 'm ' + (sec % 60) + 's'
  const h = Math.floor(sec / 3600)
  const m = Math.floor((sec % 3600) / 60)
  return h + 'h ' + m + 'm'
}
