import React from 'react';
import { string, array, func } from 'prop-types';
import { highlightSearchQuery } from '@vincent_za/utils';

import { ListWrap, Item } from '../../../shared';

class Searchlist extends React.Component {
  shouldComponentUpdate(nextProps) {
    if (nextProps.list !== this.props.list) return true;
    if (nextProps.activeItems !== this.props.activeItems) return true;
    if (nextProps.activeItem !== this.props.activeItem) return true;
    if (nextProps.searchQuery !== this.props.searchQuery) return true;
    return false;
  }

  render() {
    const { list, itemKey, activeItems, activeItem, searchQuery, onClick } = this.props;

    return (
      <ListWrap>
        {
          list.map((item) => {
            const label = itemKey ? item[itemKey] : item;
            const isActive = activeItems.includes(label) || activeItem === label;
            return (
              <Item isActive={isActive} onClick={() => onClick(item)} key={label}>
                {!searchQuery && label}
                {searchQuery && highlightSearchQuery(item, searchQuery)}
              </Item>
            );
          })
        }
      </ListWrap>
    );
  }
}

Searchlist.propTypes = {
  list: array.isRequired,
  itemKey: string,
  activeItems: array,
  activeItem: string,
  searchQuery: string,
  onClick: func.isRequired,
};

Searchlist.defaultProps = {
  itemKey: undefined,
  activeItems: [],
  activeItem: undefined,
  searchQuery: undefined,
};

export default Searchlist;
