import * as React from 'react';
import { Text } from '../Text/index';
import { string, number, oneOfType, elementType } from 'prop-types';
import { Shelf } from '../Layout/index';
import { toFinite } from 'lodash';
import Icon from '../Icon/index';

function getColor(sign) {
  if (sign === -1) return 'Red';
  if (sign === 1) return 'Green';
  return 'Mid Neutral 1';
}

function toCurrency(amount, code) {
  const formatter = new Intl.NumberFormat('en-US', {
    style: 'currency',
    currency: code,
    minimumFractionDigits: Math.floor(amount) === amount ? 0 : 2,
    maximumFractionDigits: 2,
  });

  return amount === 0 || toFinite(amount) ? formatter.format(amount) : '';
}

function getIcon(sign) {
  if (sign === -1) return 'arrow-down';
  return 'arrow-up';
}

const Stock = ({ amount, fontSize, currencyCode, as: Comp, ...rest }) => {
  const sign = Math.sign(amount);
  return (
    <Shelf gap="xxsmall">
      <Icon size={8} name={getIcon(sign)} color={getColor(sign)} />
      <Comp color={getColor(sign)} fontSize={fontSize} {...rest}>
        {toCurrency(amount, currencyCode)}
      </Comp>
    </Shelf>
  );
};

Stock.propTypes = {
  as: elementType,
  amount: oneOfType([string, number]),
  size: oneOfType([string, number]),
  currency: string,
};

Stock.defaultProps = {
  as: Text,
  amount: 0,
  fontSize: 'small',
  currency: 'GBP',
};

export default Stock;
