import classnames from 'classnames';
import AggregateCandidateVotes from "../../AggregateCandidateVotes/index.js";
import IfActive from "../../../application/IfActive/index.js";
import ElectionIcon from "../../ElectionIcon/index.js";
import { useMemo } from 'react';
import { useTrackStandardEvent } from "../../../../hooks/tracking/index.js";
import useA11yOnClick from "../../../../hooks/useA11yOnClick/index.js";
import { useResultsTableFormatContext } from '../context';
import typography from '../typography.module.scss';
import classes from './styles.module.scss';
import RowWrapper from '../RowWrapper';
const OtherCandidatesRow = function OtherCandidatesRow(props) {
  const {
    id,
    candidateIds,
    isExpanded,
    setIsExpanded,
    idx
  } = props;
  const {
    showVotes,
    expandable,
    size
  } = useResultsTableFormatContext();
  const showButton = expandable === 'expandableAggregation';
  const text = useMemo(() => {
    if (isExpanded) {
      return 'Collapse';
    }
    if (size === 'small') {
      return 'Others';
    }
    return 'Other candidates';
  }, [size, isExpanded]);
  const buttonIconType = isExpanded ? 'Collapse' : 'Expand';
  const expandButtonSize = size === 'large' ? '4' : '3';
  const track = useTrackStandardEvent({
    component: 'ResultsTable'
  });
  const clickHandler = useA11yOnClick(e => {
    // prevent the default click behavior - leaderboard might be a link
    e.preventDefault();
    setIsExpanded(prev => {
      const next = !prev;
      track({
        event: next ? 'expand' : 'collapse',
        detail: id
      });
      return next;
    });
  }, [setIsExpanded, track]);
  const buttonProps = showButton ? clickHandler : {};
  return <RowWrapper id={id} idx={idx}>
      <div role="cell">
        <div {...buttonProps} className={classes.header}>
          <span className={classes.iconContainer}>
            <IfActive active={showButton}>
              <ElectionIcon type={buttonIconType} color="warmgray-60" size={expandButtonSize} />
            </IfActive>
            <IfActive active={!showButton}>
              <ElectionIcon type="CandidateSwatch" color="warmgray-70" size="2" />
            </IfActive>
          </span>
          <span className={classnames(classes.text, classes.left, typography.cellText)}>
            {text}
          </span>
        </div>
      </div>

      <IfActive active={(!showButton || !isExpanded) && showVotes}>
        <div role="cell" className={classnames(classes.cell, typography.cellText)}>
          <AggregateCandidateVotes id={id} candidateIds={candidateIds} />
        </div>

      </IfActive>

      <IfActive active={!showButton || !isExpanded}>
        <div role="cell" className={classnames(classes.cell, classes.right, typography.cellText)}>
          <AggregateCandidateVotes id={id} candidateIds={candidateIds} format="percent" minimumFractionDigits={1} />
        </div>
      </IfActive>
    </RowWrapper>;
};
export default OtherCandidatesRow;