import { useMemo } from 'react';
import { NumericFormat, NumericFormatProps } from 'react-number-format';
import { getCurrency } from '@akinon/next/utils';
import { useLocalization } from '@akinon/next/hooks';
import { PriceProps } from '../types';
import Settings from '@theme/settings';

export const Price = (props: NumericFormatProps & PriceProps) => {
  const {
    value,
    currencyCode,
    displayType = 'text',
    useCurrencySymbol = false,
    useCurrencyAfterPrice = true,
    useCurrencySpace = true,
    useNegative = false,
    useNegativeSpace = true,
    thousandSeparator = '.',
    decimalScale = 2,
    decimalSeparator = ',',
    fixedDecimalScale = true,
    ...rest
  } = props;

  const { currency: selectedCurrencyCode } = useLocalization();
  const currencyCode_ = currencyCode || selectedCurrencyCode;

  const currency = useMemo(
    () =>
      getCurrency({
        currencyCode: currencyCode_,
        useCurrencySymbol,
        useCurrencyAfterPrice,
        useCurrencySpace
      }),
    [currencyCode_, useCurrencySymbol, useCurrencyAfterPrice, useCurrencySpace]
  );

  const numericValue =
    typeof value === 'string'
      ? parseFloat(value)
      : typeof value === 'number'
      ? value
      : 0;

  const formattedValue = Number.isFinite(numericValue)
    ? numericValue.toFixed(decimalScale)
    : '0';

  const displayValue =
    useNegative && numericValue < 0
      ? `-${useNegativeSpace ? ' ' : ''}${Math.abs(numericValue).toFixed(
          decimalScale
        )}`
      : formattedValue;

  const currentCurrencyDecimalScale = Settings.localization.currencies.find(
    (currency) => currency.code === currencyCode_
  )?.decimalScale;

  return (
    <NumericFormat
      value={displayValue}
      displayType={displayType}
      thousandSeparator={thousandSeparator}
      decimalScale={currentCurrencyDecimalScale ?? decimalScale}
      decimalSeparator={decimalSeparator}
      fixedDecimalScale={fixedDecimalScale}
      prefix={!useCurrencyAfterPrice ? currency : undefined}
      suffix={useCurrencyAfterPrice ? currency : undefined}
      {...rest}
    />
  );
};
