import React, { useEffect } from 'react'
import cx from 'classnames'
import { indexOf, mapIndexed, pluck } from 'ramda'
import MTIcon from './mt-icon'

const MTEntityList = (props) => {
  const {
    entities,
    onEntityClick,
    initialEntityKey,
    className,
    ...otherProps
  } = props
  const entityKeys = pluck('key', entities)
  const selectedEntityIdx = indexOf(initialEntityKey, entityKeys)

  const onSelect = (idx) => {
    onEntityClick(entityKeys[idx])
  }

  const handleKeyDown = (e) => {
    if (e.target.tagName === 'INPUT') return
    if (e.key === 'ArrowDown' && selectedEntityIdx !== entityKeys.length - 1) {
      const a = selectedEntityIdx + 1
      onSelect(a)
    }

    if (e.key === 'ArrowUp' && selectedEntityIdx !== 0) {
      const a = selectedEntityIdx - 1
      onSelect(a)
    }
  }

  useEffect(() => {
    document.addEventListener('keydown', handleKeyDown)
    return () => document.removeEventListener('keydown', handleKeyDown)
  }, [ initialEntityKey ])

  return (
    <div { ...otherProps } className={ cx('entity-list', className) }>
      { mapIndexed((entity, idx) => (
        <div
          key={ entity.name }
          onClick={ () => onSelect(idx) }
          className={ `entity-list__item ${initialEntityKey === entity.key ? 'entity-list__item--selected' : ''}` }
        >
          <MTIcon type={ entity.icon } className="entity-list__item__icon" />
          <div className="entity-list__item__name" key={ entity.name }>
            { entity.name }
          </div>
        </div>
      ), entities) }
    </div>
  )
}

export default MTEntityList
