export const PLAUSIBILITY_RANGES = {
  HEART_RATE: { min: 1, max: 300 },
  TEMP_C: { min: 15, max: 50 },
  SPO2: { min: 50, max: 100 },
  RESP_RATE: { min: 1, max: 80 },
  SYSTOLIC_BP: { min: 40, max: 300 },
  DIASTOLIC_BP: { min: 20, max: 200 },
  AVPU: { min: 0, max: 3 },
}

export const AVPU_OPTIONS = [
  { value: 0, label: '0 — Alert' },
  { value: 1, label: '1 — Responds to voice' },
  { value: 2, label: '2 — Responds to pain' },
  { value: 3, label: '3 — Unresponsive' },
]

export const VITAL_FIELD_DEFS = [
  { key: 'heartRate', code: 'HEART_RATE', label: 'Heart Rate', unit: 'bpm', step: '1' },
  { key: 'respRate', code: 'RESP_RATE', label: 'Respiratory Rate', unit: 'breaths/min', step: '1' },
  { key: 'systolicBp', code: 'SYSTOLIC_BP', label: 'Systolic BP', unit: 'mmHg', step: '1' },
  { key: 'diastolicBp', code: 'DIASTOLIC_BP', label: 'Diastolic BP', unit: 'mmHg', step: '1' },
  { key: 'spo2', code: 'SPO2', label: 'SpO₂', unit: '%', step: '1' },
  { key: 'tempC', code: 'TEMP_C', label: 'Temperature', unit: '°C', step: '0.1' },
  { key: 'avpu', code: 'AVPU', label: 'AVPU', unit: 'score', type: 'select' },
]

export function isPlausibleValue(code, value) {
  const range = PLAUSIBILITY_RANGES[code]
  if (!range) return true
  const numeric = Number(value)
  if (Number.isNaN(numeric)) return false
  return numeric >= range.min && numeric <= range.max
}

export function plausibilityMessage(code, value) {
  const range = PLAUSIBILITY_RANGES[code]
  if (!range) return null
  if (isPlausibleValue(code, value)) return null
  return `Value must be between ${range.min} and ${range.max}`
}

export function buildVitalsObservations(values, recordedAt = new Date().toISOString()) {
  const observations = []

  for (const field of VITAL_FIELD_DEFS) {
    const raw = values[field.key]
    if (raw === '' || raw == null) continue

    observations.push({
      observationCode: field.code,
      value: Number(raw),
      unit: field.unit,
      source: 'Manual',
      recordedAt,
    })
  }

  return observations
}

export function validateVitalsForm(values) {
  const errors = {}
  let hasValue = false

  for (const field of VITAL_FIELD_DEFS) {
    const raw = values[field.key]
    if (raw === '' || raw == null) continue

    hasValue = true
    const message = plausibilityMessage(field.code, raw)
    if (message) errors[field.key] = message
  }

  if (!hasValue) {
    errors._form = 'Enter at least one vital sign.'
  }

  return {
    valid: Object.keys(errors).length === 0,
    errors,
    observations: buildVitalsObservations(values),
  }
}

export function emptyVitalsForm() {
  return Object.fromEntries(VITAL_FIELD_DEFS.map(field => [field.key, '']))
}
