import { defaultTo, isNil, map, merge, omit, sort } from 'ramda'
import React from 'react'
import MTTable from './mt-table'
import MTIcon from './mt-icon'

class MTDataTable extends React.Component {
  constructor (props) {
    super(props)
    const { initialSort } = props
    const sorting = defaultTo({
      sortColumn: null,
      isAscending: null,
    }, initialSort)
    this.state = merge(sorting, { filterInput: '' })
    this.onSorted()
  }

  handleSort (index) {
    const { sortColumn, isAscending } = this.state
    let newAscending
    let newSortColumn

    if (index !== sortColumn) {
      newSortColumn = index
      newAscending = true
    } else if (isAscending) {
      newSortColumn = index
      newAscending = false
    } else {
      newSortColumn = null
      newAscending = null
    }

    this.setState({
      sortColumn: newSortColumn,
      isAscending: newAscending,
    }, () => this.onSorted())
  }

  onSorted () {
    if (!isNil(this.props.onSorted)) {
      this.props.onSorted(this.state.sortColumn, this.state.isAscending)
    }
  }

  render () {
    const { sortColumn, isAscending, filterInput } = this.state
    const {
      columns,
      data,
      footer,
      highlightFirstColumn,
      highlightLastColumn,
      expandLastColumn,
      zebraTable,
      filterFunction,
      filterPlaceholder,
      filterLabel,
      handleRowClick,
      rowMenu,
      className,
      tableClassName,
      tableProps,
      ...rest
    } = this.props
    const otherProps = omit([ 'onSorted', 'initialSort' ], rest)
    const headers = map((item) => item.label, columns)
    const filteredData = isNil(filterFunction) ? data : filterFunction(data, filterInput)
    let sortedData = filteredData
    if (sortColumn !== null) {
      const column = columns[sortColumn]
      const { render, key, getSortValue } = column
      const getValue = getSortValue != null
        ? getSortValue
        : render == null ? (obj) => obj[key] : render
      const modifier = isAscending ? 1 : -1
      sortedData = sort((a, b) => {
        const aValue = getValue(a)
        const bValue = getValue(b)
        if (aValue === bValue) {
          return 0
        } if (aValue < bValue) {
          return -1 * modifier
        }
        return 1 * modifier
      }, filteredData)
    }

    const rows = map((item) => map((column) => {
      const { render, key } = column
      return render == null ? item[key] : render(item)
    }, columns), sortedData)

    const tableFilter = isNil(filterFunction)
      ? null
      : (
        <div className="mt-data-table__filter">
          <div className="input input--inline input--icon">
            <label>
              <input
                type="text"
                value={ filterInput }
                onChange={ (e) => this.setState({ filterInput: e.target.value }) }
                placeholder={ filterPlaceholder }
              />
              <strong className="m-l">{ filterLabel }</strong>
              <MTIcon type="filter" />
            </label>
          </div>
        </div>
      )

    return (
      <div { ...otherProps } className={ `mt-data-table ${className}` }>
        { tableFilter }
        <MTTable
          { ...tableProps }
          data={ sortedData }
          headers={ headers }
          rows={ rows }
          footer={ footer }
          onSort={ (i) => this.handleSort(i) }
          highlightFirstColumn={ highlightFirstColumn }
          highlightLastColumn={ highlightLastColumn }
          expandLastColumn={ expandLastColumn }
          zebraTable={ zebraTable }
          handleRowClick={ handleRowClick }
          rowMenu={ rowMenu }
          className={ tableClassName }
          { ...this.state }
        />
      </div>
    )
  }
}

MTDataTable.defaultProps = {
  zebraTable: false,
  filterPlaceholder: 'Filter table...',
  filterLabel: '',
  tableClassName: '',
  className: '',
}

export default MTDataTable
