import { useMemo } from 'react';
import sortBy from "../../../utils/sorting/sortBy.js";
import AutoLayout from "../../layout/AutoLayout/index.js";
import MapLegendItem from "../MapLegendItem/index.js";
import { PartyName, CandidateName } from "../index.js";
import PropTypes from "../../../utils/prop-types/index.js";
import classes from './styles.module.scss';
const Legend = function Legend(props) {
  const {
    palettes,
    includeNoClearLeader,
    includeRunoff,
    includeFlip,
    labelType
  } = props;
  const paletteEntries = useMemo(() => {
    if (labelType === 'name') {
      return sortBy(palettes, ['palette', 'candidateId']);
    }
    const paletteSet = new Set(palettes.map(p => p.palette === 'fallback' ? 'other-party' : p.palette));
    return sortBy([...paletteSet]).map(p => ({
      palette: p
    }));
  }, [labelType, palettes, sortBy]);
  const hasPalettes = paletteEntries.length > 0;
  const [Label, labelProps] = useMemo(() => {
    if (labelType === 'name') {
      return [CandidateName, {
        format: 'short'
      }];
    }
    return [PartyName, {
      format: 'abbr'
    }];
  }, [labelType]);
  return <AutoLayout direction="horizontal" align="left" gap="2" wrap margin={{
    t: '2'
  }}>
      {hasPalettes && <div className={classes.title}>
          Leading/Won
        </div>}
      {paletteEntries.map(palette => <MapLegendItem key={palette.palette} type="palette" palette={palette.palette} label={<Label id={labelType === 'name' ? palette.candidateId : palette.palette} {...labelProps} />} />)}
      {includeRunoff && <MapLegendItem type="runoff" label="Runoff" />}
      {includeFlip && <MapLegendItem type="flip" label="Flip" />}
      {includeNoClearLeader && <MapLegendItem type="unclear" label="No clear leader" />}
    </AutoLayout>;
};
Legend.defaultProps = {
  labelType: 'party',
  includeNoClearLeader: false,
  includeRunoff: false,
  includeFlip: false
};
Legend.propTypes = {
  /**
   * A set of configurations that are used  to create the legend entries
   */
  palettes: PropTypes.arrayOf(PropTypes.shape({
    palette: PropTypes.string,
    candidateId: PropTypes.string
  })).isRequired,
  /**
   * How to display the map legend item labels
   */
  labelType: PropTypes.oneOf(['party', 'name']),
  /**
   * Whether to include the no clear leader legend item
   */
  includeNoClearLeader: PropTypes.bool,
  /**
   * Whether to include the runoff legend item
   */
  includeRunoff: PropTypes.bool,
  /**
   * Whether to include the flip legend item
   */
  includeFlip: PropTypes.bool
};
export default Legend;