// @flow
import React from 'react';
import styled from 'styled-components';
import { FormattedNumber } from 'react-intl';
import type { PercentProps } from './percent-formatter.proptypes';

const StyledWrapper = styled.span`
  span {
    &:last-child {
      margin-left: 0.1em;
    }
  }
`;

export const PercentFormatter = (props: PercentProps) => {
  const { value } = props;

  if (Number.isNaN(parseFloat(value))) {
    return <span>−</span>;
  }

  // can't use `style="percent"` due to the need to style the percent symbol
  return (
    <StyledWrapper>
      <FormattedNumber
        minimumFractionDigits={1}
        maximumFractionDigits={1}
        // eslint-disable-next-line react/style-prop-object
        style="decimal"
        {...props}
        value={value * 100} // decimal to percent
      />
      <span>%</span>
    </StyledWrapper>
  );
};

PercentFormatter.displayName = 'PercentFormatter';
