export const DEFAULT_WARD_SORT_FIELD = 'news2Score'
export const DEFAULT_WARD_SORT_DIRECTION = 'desc'

export const WARD_SORT_FIELDS = [
  { key: 'roomBed', label: 'Room' },
  { key: 'name', label: 'Patient' },
  { key: 'department', label: 'Department' },
  { key: 'news2Score', label: 'NEWS2' },
  { key: 'qsofaScore', label: 'qSOFA' },
  { key: 'sepsis', label: 'Sepsis' },
  { key: 'openAlertCount', label: 'Alerts' },
]

const SEPSIS_RANK = {
  IN_PROGRESS: 3,
  NON_COMPLIANT: 2,
  COMPLIANT: 1,
}

export function defaultSortDirection(field) {
  if (field === 'name' || field === 'roomBed' || field === 'department') return 'asc'
  return 'desc'
}

function getSortValue(encounter, field) {
  switch (field) {
    case 'name':
      return `${encounter.lastName ?? ''} ${encounter.firstName ?? ''}`.trim().toLowerCase()
    case 'roomBed':
      return (encounter.roomBed ?? encounter.room ?? '').toLowerCase()
    case 'department':
      return (encounter.department ?? '').toLowerCase()
    case 'news2Score':
      return encounter.news2Score ?? -1
    case 'qsofaScore':
      return encounter.qsofaScore ?? -1
    case 'openAlertCount':
      return encounter.openAlertCount ?? 0
    case 'sepsis':
      if (encounter.sepsisActive) return 4
      return SEPSIS_RANK[encounter.sepsisBundleStatus] ?? 0
    default:
      return encounter.news2Score ?? -1
  }
}

function compareSortValues(a, b) {
  if (typeof a === 'string' && typeof b === 'string') {
    return a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' })
  }
  if (a < b) return -1
  if (a > b) return 1
  return 0
}

export function sortEncounters(encounters, field, direction) {
  const multiplier = direction === 'asc' ? 1 : -1

  return [...encounters].sort((left, right) => {
    const primary = compareSortValues(getSortValue(left, field), getSortValue(right, field)) * multiplier
    if (primary !== 0) return primary
    return (right.news2Score ?? 0) - (left.news2Score ?? 0)
  })
}
