import PropTypes from 'prop-types';
import { useCandidateResults } from "../../../hooks/election/index.js";
import { getFormattedCandidateVotes } from "../../../utils/election/index.js";
import customizable from "../../../utils/css/customizable.js";
import DataAnimation from '../DataAnimation';

/**
 * The number of votes received by a candidate.
 *
 * This component also adds the `int-style-CandidateVotes`
 * class for styling the percent sign.
 */
const CandidateVotes = function CandidateVotes(props) {
  const {
    id,
    candidateId,
    format,
    minimumFractionDigits,
    maximumFractionDigits
  } = props;
  const results = useCandidateResults(id, candidateId);
  const votes = getFormattedCandidateVotes(results, {
    format,
    minimumFractionDigits,
    maximumFractionDigits
  });
  if (!votes) return null;
  if (!votes) {
    return null;
  }
  if (format !== 'percent') {
    return <DataAnimation trigger={votes}>
        {votes}
      </DataAnimation>;
  }
  const number = votes.replace('%', '');
  return <>
      <DataAnimation trigger={number}>
        {number}
      </DataAnimation>
      <span className={customizable('CandidateVotesPctSign')}>
        %
      </span>
    </>;
};
CandidateVotes.defaultProps = {
  format: 'number',
  minimumFractionDigits: undefined,
  maximumFractionDigits: 1
};
CandidateVotes.propTypes = {
  /**
   * The ID of the results to use.
   */
  id: PropTypes.string.isRequired,
  /**
   * The ID of the candidate whose vote count you want to format.
   */
  candidateId: PropTypes.string.isRequired,
  /**
   * The format to use.
   */
  format: PropTypes.oneOf(['number', 'percent', 'sentence']),
  /**
   * The minimum number of decimal places to render
   */
  minimumFractionDigits: PropTypes.number,
  /**
   * The maximum number of decimal places to render
   */
  maximumFractionDigits: PropTypes.number
};
export default CandidateVotes;