import { Box } from '@mui/material'
import type { Ref } from 'react'
import { Note, Prefix, Series, Suffix, Value } from '../formula'
import { styles } from '../formula/style'
import { Separator } from './separator'
import type { SpreadDataItem } from './types'

export interface SpreadUIProps {
  items: readonly SpreadDataItem[]
  /** Number formatter — applied to each item's `min` and `max`. */
  formatter?: (value: number) => string
  /** Forwarded to the root `<Box>` so consumers can capture the DOM (PNG export). */
  ref?: Ref<HTMLDivElement>
}

/**
 * Pure presentational component for the Spread widget. Each item renders as
 * a row containing (in order): optional `Series` avatar, a body with
 * `[prefix] min — max [suffix]` plus optional `Note`. Reuses the Formula
 * primitives ({@link Series}, {@link Prefix}, {@link Value}, {@link Suffix},
 * {@link Note}) and the Formula row styles so Spread and Formula stay
 * visually aligned when used together.
 */
export function SpreadUI({ items, formatter, ref }: SpreadUIProps) {
  const fmt = formatter ?? ((n: number) => String(n))
  return (
    <Box ref={ref} sx={styles.root}>
      {items.map((item, i) => (
        // Composite of series name + min/max bounds for stability across
        // reorders; falls back to the index when bounds happen to collide.
        <Box
          key={`spread-${item.series?.name ?? ''}-${item.min}-${item.max}-${i}`}
          sx={styles.row}
        >
          {item.series ? (
            <Series name={item.series.name} color={item.series.color} />
          ) : null}
          <Box sx={styles.body}>
            <Box sx={styles.valueRow}>
              {item.prefix ? <Prefix>{item.prefix}</Prefix> : null}
              <Value color={item.color}>{fmt(item.min)}</Value>
              <Separator />
              <Value color={item.color}>{fmt(item.max)}</Value>
              {item.suffix ? <Suffix>{item.suffix}</Suffix> : null}
            </Box>
            {item.note ? <Note>{item.note}</Note> : null}
          </Box>
        </Box>
      ))}
    </Box>
  )
}
