import { type FormulaWidgetState, type ValueProps } from '../types'
import { Item } from './item'
import { defaultFormatter } from '../../utils/formatter'
import { useWidgetSelector } from '../../stores/use-widget-selector'

/**
 * Displays the formatted numeric value for a formula widget data item, applying the widget's formatter and color.
 */
export function Value({ id, index = 0, ...props }: ValueProps) {
  const { value, color, formatter } = useWidgetSelector(id, (w) => {
    const widget = w as FormulaWidgetState | undefined
    return {
      value: widget?.data?.[index]?.value,
      color: widget?.data?.[index]?.color,
      formatter: widget?.formatter ?? defaultFormatter,
    }
  })

  return (
    <Item TypographyProps={{ color }} {...props}>
      {formatter(value ?? 0)}
    </Item>
  )
}
