import React from 'react'
import { DropdownButton, MenuItem, ControlLabel, HelpBlock } from 'react-bootstrap'

export class FormDropdown extends React.Component {

  constructor (props) {
    super(props)
    this.state = {
      selectedIdx: -1
    }
    this.handleSelect = this.handleSelect.bind(this)
    this.handleToggle = this.handleToggle.bind(this)
  }

  handleSelect (eventKey, event) {
    this.setState({ selectedIdx: eventKey })
    if (eventKey === 'other') {
      this.props.onSelect('other_selected')
      return
    }
    const value = this.props.options[eventKey]
    if (this.props.onSelect !== undefined) {
      this.props.onSelect(value)
    }
  }

  handleToggle (isOpen) {
    if (this.props.onToggle !== undefined) {
      this.props.onToggle(isOpen)
    }
  }

  render () {
    let controlLabel = null
    if (this.props.controlLabel !== undefined) {
      controlLabel = <ControlLabel>{this.props.controlLabel}</ControlLabel>
    }
    let helpBlock = null
    if (this.props.controlHelp !== undefined) {
      helpBlock = <HelpBlock className='formHelpBox'>{this.props.controlHelp}</HelpBlock>
    }
    let items = this.props.options.map((item, idx) => {
      return <MenuItem key={`${idx}`} eventKey={idx}>{item}</MenuItem>
    })
    items.push(<MenuItem key={'other'} eventKey={'other'}><i>Other</i></MenuItem>)
    let titleStr = this.props.valuePlaceholder
    if (this.state.selectedIdx !== -1) {
      if (this.state.selectedIdx === 'other') {
        titleStr = 'Other'
      } else {
        titleStr = this.props.options[this.state.selectedIdx]
      }
    }
    return (
      <div style={{ display: 'inline-block', marginBottom: '15px' }}>
        {controlLabel}
        {helpBlock}
        <DropdownButton
          id={this.props.controlId}
          title={titleStr}
          onSelect={this.handleSelect}
          onToggle={this.handleToggle}
          disabled={this.props.disabled}
        >
          {items}
        </DropdownButton>
      </div>
    )
  }
}

FormDropdown.defaultProps = {
  options: []
}

FormDropdown.propTypes = {
  controlId: React.PropTypes.string,
  controlLabel: React.PropTypes.string,
  controlHelp: React.PropTypes.string,
  valuePlaceholder: React.PropTypes.string,
  onSelect: React.PropTypes.func,
  onToggle: React.PropTypes.func,
  disabled: React.PropTypes.bool,
  options: React.PropTypes.arrayOf(React.PropTypes.string)
}
