import React, { Component } from 'react'
import cx from 'classnames'
import PropTypes from 'prop-types'
import { addIndex, isArrayLike, map, omit } from 'ramda'

const mapIndexed = addIndex(map)

class MTTabs extends Component {
  constructor (props) {
    const { initialTabIndex } = props
    super(props)
    this.state = {
      selectedTabIndex: initialTabIndex,
    }
  }

  selectTabIndex (idx) {
    this.setState({ selectedTabIndex: idx })
    this.props.onChange(idx)
  }

  render () {
    const {
      tabs,
      navLabels,
      className,
      ...rest
    } = this.props
    const otherProps = omit([ 'initialTabIndex' ], rest)
    const { selectedTabIndex } = this.state
    const tabNav = mapIndexed((item, idx) => {
      const navClass = cx('mt-tab-nav__item', { 'is-active': selectedTabIndex === idx })
      return (
        <li
          className={ navClass }
          key={ idx }
          onClick={ () => this.selectTabIndex(idx) }
        >
          <span>{ item }</span>
        </li>
      )
    }, navLabels)

    const tabItem = (
      <div className="mt-tab">
        { tabs[selectedTabIndex] }
      </div>
    )

    return (
      <div { ...otherProps } className={ cx('mt-tabs', className) }>
        <nav className="mt-tab-nav">
          { tabNav }
        </nav>
        { tabItem }
      </div>
    )
  }
}

MTTabs.defaultProps = {
  initialTabIndex: 0,
  navLabels: [],
  onChange: () => {},
}

MTTabs.propTypes = {
  initialTabIndex: PropTypes.number,
  tabs: PropTypes.arrayOf(PropTypes.element).isRequired,
  navLabels: (props, propName, componentName) =>
    !(isArrayLike(props[propName]) || props[propName].length !== props.tabs.length) && new Error(
      `Invalid prop ${propName} supplied to ${componentName}. Must be array of same length as tabs.`
    ),
  onChange: PropTypes.func,
}

export default MTTabs
