const BLOOD_TYPE_LABELS = {
  APositive: 'A+',
  ANegative: 'A-',
  BPositive: 'B+',
  BNegative: 'B-',
  AbPositive: 'AB+',
  AbNegative: 'AB-',
  OPositive: 'O+',
  ONegative: 'O-',
  'A+': 'A+',
  'A-': 'A-',
  'B+': 'B+',
  'B-': 'B-',
  'AB+': 'AB+',
  'AB-': 'AB-',
  'O+': 'O+',
  'O-': 'O-',
}

const DEPARTMENT_LABELS = {
  Icu: 'ICU',
  GeneralMedicine: 'General Medicine',
  Emergency: 'Emergency',
  Cardiology: 'Cardiology',
  Surgery: 'Surgery',
  Pediatrics: 'Pediatrics',
  ICU: 'ICU',
  GENERAL_MEDICINE: 'General Medicine',
  EMERGENCY: 'Emergency',
  CARDIOLOGY: 'Cardiology',
  SURGERY: 'Surgery',
  PEDIATRICS: 'Pediatrics',
}

const GENDER_LABELS = {
  M: 'Male',
  F: 'Female',
  O: 'Other',
  U: 'Unknown',
}

export function formatBloodType(value) {
  if (value == null || value === '') return '—'
  return BLOOD_TYPE_LABELS[value] ?? String(value)
}

export function formatDepartment(value) {
  if (value == null || value === '') return '—'
  return DEPARTMENT_LABELS[value] ?? String(value).replace(/_/g, ' ')
}

export function formatGender(value) {
  if (value == null || value === '') return '—'
  return GENDER_LABELS[value] ?? value
}

export function computeAge(dateOfBirth, asOf = new Date()) {
  if (!dateOfBirth) return null
  const dob = new Date(dateOfBirth)
  if (Number.isNaN(dob.getTime())) return null

  let age = asOf.getFullYear() - dob.getFullYear()
  const monthDelta = asOf.getMonth() - dob.getMonth()
  if (monthDelta < 0 || (monthDelta === 0 && asOf.getDate() < dob.getDate())) {
    age -= 1
  }
  return age
}

export function formatDateOfBirth(dateOfBirth) {
  if (!dateOfBirth) return '—'
  const d = new Date(dateOfBirth)
  if (Number.isNaN(d.getTime())) return dateOfBirth
  return d.toLocaleDateString([], { year: 'numeric', month: 'short', day: 'numeric' })
}

export function formatDobWithAge(dateOfBirth) {
  const formatted = formatDateOfBirth(dateOfBirth)
  const age = computeAge(dateOfBirth)
  if (age == null) return formatted
  return `${formatted} (${age}y)`
}

export function hasKnownAllergies(allergies) {
  return Boolean(allergies?.trim())
}

export function formatAllergiesDisplay(allergies) {
  return hasKnownAllergies(allergies) ? allergies.trim() : 'NKDA'
}
