import React from 'react'
import { NumericFormat } from 'react-number-format'

import { largeNumConversion } from '../../services/HelperServiceTyped'
import { type NumberFormatterProps } from './ScoreCardType'

const NumberFormatter = ({
  value,
  decimalScale,
  truncateValues = false,
  currency,
  additionalMetricValueSuffix = '',
  allowNegativeValue = false,
}: NumberFormatterProps) => {
  const currencySuffix =
    currency?.currencyCode && currency?.currencyCode !== 'USD'
      ? ` ${currency?.currencyCode}`
      : undefined

  const metricValue = truncateValues ? largeNumConversion(value).val : value
  const valueSuffix = truncateValues ? largeNumConversion(value).suffix : null

  const metricValueSuffix = `${valueSuffix ? `${valueSuffix} ` : ''}${
    currencySuffix ? currencySuffix : ''
  }`

  return (
    <NumericFormat
      value={
        allowNegativeValue && metricValue
          ? metricValue
          : Math.abs(Number(metricValue))
      }
      displayType='text'
      decimalScale={decimalScale}
      fixedDecimalScale={!!currency?.currencyCode || !!decimalScale}
      thousandSeparator
      prefix={currency?.currencySymbol}
      suffix={`${metricValueSuffix}${additionalMetricValueSuffix}`}
    />
  )
}

export default NumberFormatter
