import React, { Component } from 'react'
import { filter, omit } from 'ramda'
import MTIcon from './mt-icon'
import matchesInput from './matches-input'

class MTFilter extends Component {
  constructor (props) {
    super(props)
    this.state = {
      filterValue: '',
    }

    this.handleFilterChange = this.handleFilterChange.bind(this)
  }

  componentDidUpdate (prevProps) {
    if (prevProps.data !== this.props.data) {
      const hits = filter((item) =>
        matchesInput(this.props.filterProps, this.state.filterValue, item), this.props.data
      )
      this.props.onFilterChange(hits)
    }
  }

  handleFilterChange (e) {
    const { filterProps, onFilterChange, data } = this.props
    this.setState({ filterValue: e.target.value })
    const hits = filter((item) => matchesInput(filterProps, e.target.value, item), data)
    onFilterChange(hits)
  }

  render () {
    const { filterValue } = this.state
    const {
      filterPlaceholder,
      filterIconType,
      className,
      ...rest
    } = this.props
    const otherProps = omit([ 'filterProps', 'onFilterChange', 'data' ], rest)
    return (
      <div { ...otherProps } className={ `mt-filter input input--inline input--icon ${className}` }>
        <label>
          <input
            type="text"
            value={ filterValue }
            onChange={ this.handleFilterChange }
            placeholder={ filterPlaceholder }
          />
          <MTIcon type={ filterIconType } />
        </label>
      </div>
    )
  }
}

MTFilter.defaultProps = {
  data: [],
  filterPlaceholder: 'Filter...',
  filterProps: [],
  filterIconType: 'filter',
}

export default MTFilter
