import { Tag } from 'antd'
import moment from 'moment'

const COMPONENT_NAMES: Record<string, string> = {
  classic_restore: 'Classic Restore',
  coprocessor_worker: 'Coprocessor Worker',
  data_migration: 'Data Migration',
  dumpling: 'Dumpling',
  pd: 'PD',
  pd_scheduling: 'PD Scheduling',
  pd_tso: 'PD TSO',
  resource_manager: 'Resource Manager',
  schema_manager: 'Schema Manager',
  tidb: 'TiDB',
  tidb_worker: 'TiDB Worker',
  tiflash_compute: 'TiFlash Compute',
  tiflash_write: 'TiFlash Write',
  tikv: 'TiKV',
  tikv_worker: 'TiKV Worker',
  tiproxy: 'TiProxy',
  tibr_autobackup: 'TiBR Auto Backup',
  tibr_restore: 'TiBR Restore',
  tibrgc_t2_dfsgc: 'TiBR GC T2',
  tibrgc_t3_archive: 'TiBR GC T3'
}

const STATUS_COLORS: Record<string, string> = {
  approval_pending_create: 'gold',
  approval_creating: 'processing',
  approval_reconcile_required: 'error',
  pending_approval: 'gold',
  approved: 'cyan',
  running: 'processing',
  preparing: 'processing',
  applying: 'processing',
  waiting_conflict: 'orange',
  waiting_manual_apply: 'cyan',
  cancelling: 'orange',
  completed: 'success',
  succeeded: 'success',
  partial_failed: 'volcano',
  failed: 'error',
  rejected: 'error',
  cancelled: 'default',
  skipped: 'default',
  pending: 'default'
}

export const TERMINAL_PLAN_STATUSES = new Set([
  'completed',
  'partial_failed',
  'failed',
  'rejected',
  'cancelled'
])

export const componentName = (component: string) =>
  COMPONENT_NAMES[component] ?? titleCase(component)

export const componentSelectorName = (selector: string) => {
  const [clusterType, component] = selector.split('/')
  if (!component) return componentName(selector)
  return `${
    clusterType === 'SHARED_POOL' ? 'Pool' : 'Cluster'
  } · ${componentName(component)}`
}

export const applyGroupName = (group: string) => {
  const normalized = group
    .replace(/^shared_pool_/, '')
    .replace(/^logical_cluster_/, '')
  return componentName(normalized)
}

export const executionModeName = (mode?: string) =>
  mode === 'step_by_step' ? 'Apply step by step' : 'Run all in sequence'

export const titleCase = (value: string) =>
  value
    .split('_')
    .filter(Boolean)
    .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
    .join(' ')

export const renderUpgradeStatus = (status?: string) => {
  const normalized = status || 'unknown'
  return (
    <Tag color={STATUS_COLORS[normalized] || 'default'}>
      {titleCase(normalized)}
    </Tag>
  )
}

export const formatDateTime = (value?: string) =>
  value ? moment(value).local().format('YYYY-MM-DD HH:mm:ss') : '-'
