export function emptyThresholdForm() {
  return {
    observationCode: '',
    displayName: '',
    unit: '',
    criticalLow: '',
    warningLow: '',
    warningHigh: '',
    criticalHigh: '',
  }
}

function parseOptionalNumber(value) {
  if (value === '' || value == null) return null
  const numeric = Number(value)
  return Number.isNaN(numeric) ? NaN : numeric
}

export function thresholdFormToPayload(values) {
  return {
    observationCode: values.observationCode.trim(),
    displayName: values.displayName.trim(),
    unit: values.unit.trim(),
    criticalLow: parseOptionalNumber(values.criticalLow),
    warningLow: parseOptionalNumber(values.warningLow),
    warningHigh: parseOptionalNumber(values.warningHigh),
    criticalHigh: parseOptionalNumber(values.criticalHigh),
  }
}

export function thresholdToForm(threshold) {
  return {
    observationCode: threshold.observationCode ?? '',
    displayName: threshold.displayName ?? '',
    unit: threshold.unit ?? '',
    criticalLow: threshold.criticalLow ?? '',
    warningLow: threshold.warningLow ?? '',
    warningHigh: threshold.warningHigh ?? '',
    criticalHigh: threshold.criticalHigh ?? '',
  }
}

export function validateThresholdForm(values) {
  const errors = {}
  if (!values.observationCode?.trim()) errors.observationCode = 'Observation code is required.'
  if (!values.displayName?.trim()) errors.displayName = 'Display name is required.'
  if (!values.unit?.trim()) errors.unit = 'Unit is required.'

  const criticalLow = parseOptionalNumber(values.criticalLow)
  const warningLow = parseOptionalNumber(values.warningLow)
  const warningHigh = parseOptionalNumber(values.warningHigh)
  const criticalHigh = parseOptionalNumber(values.criticalHigh)

  for (const [key, value] of Object.entries({
    criticalLow,
    warningLow,
    warningHigh,
    criticalHigh,
  })) {
    if (Number.isNaN(value)) errors[key] = 'Must be a valid number.'
  }

  if (
    criticalLow != null && !Number.isNaN(criticalLow)
    && warningLow != null && !Number.isNaN(warningLow)
    && criticalLow >= warningLow
  ) {
    errors.warningLow = 'Warning low must be greater than critical low.'
  }

  if (
    warningLow != null && !Number.isNaN(warningLow)
    && warningHigh != null && !Number.isNaN(warningHigh)
    && warningLow >= warningHigh
  ) {
    errors.warningHigh = 'Warning high must be greater than warning low.'
  }

  if (
    warningHigh != null && !Number.isNaN(warningHigh)
    && criticalHigh != null && !Number.isNaN(criticalHigh)
    && warningHigh >= criticalHigh
  ) {
    errors.criticalHigh = 'Critical high must be greater than warning high.'
  }

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

export function formatThresholdValue(value) {
  if (value == null || value === '') return '—'
  return String(value)
}
