import { Chip, type ChipProps } from '@mui/material'
import type { DeltaSeverity } from './types'

export interface DeltaProps {
  /** Numeric magnitude. Used for the default percent label and severity inference. */
  value: number
  /** Pre-formatted label override; skips the default percent formatter. */
  label?: string
  /**
   * Visual treatment. When omitted it's derived from the sign of `value`:
   * `>0 → 'positive'`, `<0 → 'negative'`, `=0 → 'neutral'`.
   */
  severity?: DeltaSeverity
  /** Override the default `Intl.NumberFormat({style:'percent'})` formatter. */
  format?: (value: number) => string
  ChipProps?: ChipProps
}

const defaultPercentFormatter = new Intl.NumberFormat(undefined, {
  style: 'percent',
  signDisplay: 'always',
  maximumFractionDigits: 1,
})

const SEVERITY_TO_COLOR: Record<DeltaSeverity, ChipProps['color']> = {
  positive: 'success',
  negative: 'error',
  neutral: 'default',
}

/**
 * Comparative delta rendered as a small filled chip. Colour is driven by
 * `severity` (or the sign of `value`); content is `label`, the result of
 * `format(value)`, or the default percent format.
 */
export function Delta({
  value,
  label,
  severity,
  format,
  ChipProps: chipProps,
}: DeltaProps) {
  const resolvedSeverity = severity ?? inferSeverity(value)
  const text =
    label ?? (format ? format(value) : defaultPercentFormatter.format(value))
  return (
    <Chip
      size='small'
      color={SEVERITY_TO_COLOR[resolvedSeverity]}
      label={text}
      sx={{ fontWeight: 600 }}
      {...chipProps}
    />
  )
}

function inferSeverity(value: number): DeltaSeverity {
  if (value > 0) return 'positive'
  if (value < 0) return 'negative'
  return 'neutral'
}
