import React, {useMemo} from 'react';
import {StyleProp, View, ViewStyle} from 'react-native';
import {useTranslation} from 'react-i18next';

import {Typography, TypographyProps} from '../../_core/Typography';
import {TYPOGRAPHY_STYLES} from '../../_core/Typography/styles';
import {DECIMAL_LINE_HEIGHT_RATIO, styles} from './styles';
import {splitCurrencyParts} from './utils';

export interface CurrencyAmountProps extends Omit<TypographyProps, 'children'> {
  amount: number;
  decimalSizeRatio?: number;
  containerStyle?: StyleProp<ViewStyle>;
}

export function CurrencyAmount({
  amount,
  decimalSizeRatio = 0.5,
  variant = 's',
  containerStyle,
  ...typographyProps
}: CurrencyAmountProps) {
  const {i18n} = useTranslation();
  const locale = i18n.language;

  const {integerText, fractionText} = useMemo(
    () => splitCurrencyParts(locale, amount),
    [amount, locale],
  );

  const {fontSize} = TYPOGRAPHY_STYLES[variant];
  const decimalFontSize = fontSize * decimalSizeRatio;

  return (
    <View style={[styles.container, containerStyle]}>
      <Typography variant={variant} {...typographyProps}>
        {`$` + integerText}
      </Typography>
      {fractionText ? (
        <Typography
          {...typographyProps}
          style={[
            typographyProps.style,
            {
              fontSize: decimalFontSize,
              lineHeight: decimalFontSize * DECIMAL_LINE_HEIGHT_RATIO,
            },
          ]}>
          {fractionText}
        </Typography>
      ) : null}
    </View>
  );
}
