import { Box } from '@mui/material'
import type { Ref } from 'react'
import type { FormulaDataItem } from './types'
import { Delta } from './delta'
import { Note } from './note'
import { Prefix } from './prefix'
import { Series } from './series'
import { Suffix } from './suffix'
import { Value } from './value'
import { styles } from './style'

export interface FormulaUIProps {
  items: readonly FormulaDataItem[]
  /** Number formatter — applied to each item's `value`. */
  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 Formula widget. Each item renders as
 * a row containing (in order): optional `Series` avatar, a body with
 * `[prefix] value [suffix]` plus optional `Note`, and an optional `Delta`
 * chip pushed to the right edge.
 *
 * For fully custom layouts, compose {@link Series}, {@link Prefix},
 * {@link Value}, {@link Suffix}, {@link Note}, and {@link Delta} directly
 * instead of passing `items`.
 */
export function FormulaUI({ items, formatter, ref }: FormulaUIProps) {
  return (
    <Box ref={ref} sx={styles.root}>
      {items.map((item, i) => (
        // Series name is the closest stable id; fall back to the literal
        // value (numeric KPIs rarely repeat with the same prefix/suffix).
        <Box
          key={`formula-${item.series?.name ?? `${item.prefix ?? ''}${item.value}${item.suffix ?? ''}`}-${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}>
                {formatter ? formatter(item.value) : String(item.value)}
              </Value>
              {item.suffix ? <Suffix>{item.suffix}</Suffix> : null}
            </Box>
            {item.note ? <Note>{item.note}</Note> : null}
          </Box>
          {item.delta ? (
            <Box sx={styles.delta}>
              <Delta
                value={item.delta.value}
                label={item.delta.label}
                severity={item.delta.severity}
              />
            </Box>
          ) : null}
        </Box>
      ))}
    </Box>
  )
}
