import { Badge } from 'antd'

import {
  OperationInstancePhase,
  OperationActionStatus
} from 'apiClient/services/devops/interface'

export const WEIGHTS: Record<string, number> = {
  resource_pool_id: 1,
  cluster_id: 2,
  project_id: 3,
  tenant_id: 4,
  tenant_region: 5,
  service_plan: 6
}

type ParamDefinition = {
  optional?: boolean
}

const getParamSortGroup = (
  key: string,
  paramDefinitions?: Record<string, ParamDefinition | undefined>
) => {
  if (WEIGHTS[key] !== undefined) {
    return 0
  }

  return paramDefinitions?.[key]?.optional === true ? 2 : 1
}

export const SortByWeight = (
  m: { [key: string]: any },
  paramDefinitions?: Record<string, ParamDefinition | undefined>
) => {
  const keys = Object.keys(m)
  const definitions = paramDefinitions || m

  keys.sort((a, b) => {
    const groupA = getParamSortGroup(a, definitions)
    const groupB = getParamSortGroup(b, definitions)
    if (groupA !== groupB) {
      return groupA - groupB
    }

    const weightA = WEIGHTS[a] || Number.MAX_SAFE_INTEGER
    const weightB = WEIGHTS[b] || Number.MAX_SAFE_INTEGER
    if (weightA === weightB) {
      return a.localeCompare(b)
    }

    return weightA - weightB
  })

  const sortedMap: Record<string, any> = {}
  keys.forEach((key) => {
    sortedMap[key] = m[key]
  })
  return sortedMap
}

export const InstancePhaseDisplay = ({
  phase
}: {
  phase: OperationInstancePhase | undefined
}) => {
  const colorMap = new Map<OperationInstancePhase, string>([
    [OperationInstancePhase.draft, 'grey'],
    [OperationInstancePhase.created, 'green'],
    [OperationInstancePhase.approving, 'orange'],
    [OperationInstancePhase.withdrawn, 'red'],
    [OperationInstancePhase.pending, 'grey'],
    [OperationInstancePhase.running, 'blue'],
    [OperationInstancePhase.succeeded, 'green'],
    [OperationInstancePhase.failed, 'red'],
    [OperationInstancePhase.canceled, 'black']
  ])

  return (
    <Badge
      color={colorMap.get(phase ?? OperationInstancePhase.pending) ?? 'grey'}
      text={phase ? phase.toString() : 'unknown'}
    />
  )
}

export const ActionStatusDisplay = ({
  status
}: {
  status: OperationActionStatus | undefined
}) => {
  const colorMap = new Map<OperationActionStatus, string>([
    [OperationActionStatus.created, 'green'],
    [OperationActionStatus.running, 'blue'],
    [OperationActionStatus.succeeded, 'green'],
    [OperationActionStatus.failed, 'red'],
    [OperationActionStatus.unknown, 'black'],
    [OperationActionStatus.skipped, 'grey']
  ])

  return (
    <Badge
      color={colorMap.get(status ?? OperationActionStatus.unknown) ?? 'black'}
      text={status ? status.toString() : 'unknown'}
    />
  )
}
