import React from 'react'
import PropTypes from 'prop-types'
import {
  any,
  append,
  map,
  prop,
  reject,
} from 'ramda'
import { curry, eq } from 'yafu'
import cx from 'classnames'

import { selectionType, suggestionsType } from './select-prop-types'

import MTIcon from './mt-icon'

const isSelected = curry((selection, id) =>
  any(eq(id), selection)
)

const createUpdateSelectionFn = (props) => {
  const { multiple } = props
  if (!multiple) return (_selection, item) => [ item ]

  return (selection, id) => (isSelected(selection, id)
    ? reject(eq(id), selection)
    : append(id, selection))
}

const Item = (props) => {
  const {
    suggestion,
    selected,
    onClick,
    suggestionRenderer: Renderer,
  } = props

  const className = cx('mt-button-select__item', {
    'mt-button-select__item--selected': selected,
  })

  return (
    <div
      className={ className }
      onClick={ onClick }
    >
      <span className="mt-button-select__item__label">
        <Renderer { ...suggestion } />
      </span>
      { selected && (
        <div className="mt-button-select__item__checkmark">
          <MTIcon type="success" />
        </div>
      ) }
    </div>
  )
}

const MTButtonSelect = (props) => {
  const {
    suggestions,
    selection,
    onChange,
    suggestionRenderer,
    className,
    ...otherProps
  } = props

  const updateSelection = createUpdateSelectionFn(props)
  const createClickHandler = (suggestion) => () => {
    const { id } = suggestion
    const newSelection = updateSelection(selection, id)
    onChange(newSelection)
  }

  return (
    <div { ...otherProps } className={ cx('mt-button-select', className) }>
      { map((suggestion) => (
        <Item
          key={ suggestion.id }
          suggestion={ suggestion }
          suggestionRenderer={ suggestionRenderer }
          selected={ isSelected(selection, suggestion.id) }
          onClick={ createClickHandler(suggestion) }
        />
      ), suggestions) }
    </div>
  )
}

MTButtonSelect.propTypes = {
  multiple: PropTypes.bool,
  suggestions: suggestionsType.isRequired,
  selection: selectionType,
  onChange: PropTypes.func,
  suggestionRenderer: PropTypes.func,
}

MTButtonSelect.defaultProps = {
  multiple: false,
  selection: [],
  onChange: () => {},
  suggestionRenderer: prop('label'),
}

export default MTButtonSelect
