import React from 'react'
import {
  ControlLabel,
  HelpBlock,
  Form,
  ListGroup,
  ListGroupItem,
  Button,
  Glyphicon,
  InputGroup,
  Tooltip,
  OverlayTrigger
} from 'react-bootstrap'
import { FormText } from './FormText'
import { FormValidationType } from './FormValidation'
import './Forms.scss'

export class FormTextList extends React.Component {

  constructor (props) {
    super(props)
    this.state = {
      entries: []
    }
    this.addEntry = this.addEntry.bind(this)
    this.removeEntry = this.removeEntry.bind(this)
    this.handleFormValue = this.handleFormValue.bind(this)
  }

  addEntry (entry) {
    let entries = this.state.entries
    let values = []
    this.props.values.forEach((value) => { values.push(value) })
    entries.push(values)
    this.props.listHandler(entries)
    this.setState({ entries: entries })
  }

  removeEntry (entryIdx) {
    let entries = this.state.entries
    entries.splice(entryIdx, 1)
    this.props.listHandler(entries)
    this.setState({ entries: entries })
  }

  handleFormValue (value, idx) {
    const values = this.props.values
    values[idx] = value
    this.props.valueHandlers[idx](value)
  }

  render () {
    // Render the label for this control.
    let controlLabel = null
    if (this.props.controlLabel !== undefined) {
      controlLabel = <ControlLabel>{this.props.controlLabel}</ControlLabel>
    }

    // Render the help block for this control.
    let helpBlock = null
    if (this.props.controlHelp !== undefined) {
      helpBlock = <HelpBlock className='formHelpBox'>{this.props.controlHelp}</HelpBlock>
    }

    // Render any entries that have been added.
    let addedEntries = null
    let listGroups = []

    this.state.entries.forEach((values, idx) => {
      // Populate the appropriate listgroups with our value.
      values.map((value, valueIdx) => {
        // Generate a ListGroup for this index if it doesn't already exist.
        if (listGroups.length < valueIdx + 1) {
          listGroups.push([])
        }
        listGroups[valueIdx].push(<ListGroupItem key={idx}>{value}</ListGroupItem>)
      })
    })

    if (this.state.entries.length > 0) {
      const listGroupItems = this.state.entries.map((entry, idx) => {
        return (
          <ListGroupItem key={idx} style={{ padding: '4px' }}>
            <Button onClick={() => { this.removeEntry(idx) }}bsStyle='link'>
              <Glyphicon glyph='trash' />
            </Button>
          </ListGroupItem>
        )
      })
      listGroups.push(<ListGroup>{listGroupItems}</ListGroup>)
      listGroups = listGroups.map((listGroupItems, idx) => {
        return (
          <div key={idx} style={{
            display: 'inline-block',
            marginRight: `${this.props.formSpacing}`,
            marginBottom: '-10px'
          }}>
            <ListGroup style={{ width: `${this.props.valueWidths[idx]}`, marginBottom: '0px' }}>
              {listGroupItems}
            </ListGroup>
          </div>)
      })
      addedEntries = <div>{listGroups}</div>
    }

    // Iterate through our validations to form our list of validation values.
    const validations = this.props.valueValidations

    // Plus button only gets rendered if all forms are validated a'ok.
    let plusButton = null
    let formsAreValid = true
    for (let i = 0; i < validations.length; i++) {
      if (validations[i].type !== FormValidationType.SUCCESS) {
        formsAreValid = false
        break
      }
    }
    if (formsAreValid) {
      const tooltip = (
        <Tooltip id='tooltip'>Use to add additional entries.</Tooltip>
      )
      plusButton = (
        <OverlayTrigger placement='bottom' overlay={tooltip}>
          <Button onClick={() => {
            this.addEntry()
            // Clear all of our current values.
            this.props.values.forEach((value, idx) => {
              this.props.valueHandlers[idx]('')
            })
          }}>
            <Glyphicon glyph='plus' />
          </Button>
        </OverlayTrigger>
      )
    }

    // Get our list of forms.
    let forms = this.props.values.map((value, idx) => {
      // Deterine if we're rendering something before the text-field.
      const valuePrefixes = this.props.valuePrefixes
      let valuePrefix = null
      if (valuePrefixes !== undefined) {
        valuePrefix = valuePrefixes[idx]
        if (valuePrefix === undefined) {
          valuePrefix = null
        }
      }
      let inputBefore = null
      if (valuePrefix !== null) {
        inputBefore = <InputGroup.Addon>{valuePrefix}</InputGroup.Addon>
      }
      const controlId = `${this.props.controlId}_${idx}`
      return (
        <div key={controlId} style={{ display: 'inline-block', marginRight: `${this.props.formSpacing}` }}>
          <FormText
            controlId={controlId}
            valuePlaceholder={this.props.valuePlaceholders[idx]}
            value={value}
            validation={validations[idx]}
            inputBefore={inputBefore}
            valueHandler={(value) => { this.handleFormValue(value, idx) }}
            width={this.props.valueWidths[idx]}
          />
        </div>
      )
    })

    // Now form our form of forms.
    let formEntry = (
      <Form inline onSubmit={(event) => { event.preventDefault(); this.addEntry() }}>
        {forms}
        {' '}
        {plusButton}
      </Form>
    )

    return (
      <div style={{ display: 'inline-block' }}>
        {controlLabel}
        {helpBlock}
        {addedEntries}
        {formEntry}
      </div>
    )
  }
}

FormTextList.defaultProps = {
  listHandler: (entries) => {},
  formSpacing: '10px'
}

FormTextList.propTypes = {
  controlId: React.PropTypes.string,
  controlLabel: React.PropTypes.string,
  controlHelp: React.PropTypes.string,
  valuePlaceholders: React.PropTypes.arrayOf(React.PropTypes.string),
  values: React.PropTypes.arrayOf(React.PropTypes.string).isRequired,
  valueValidations: React.PropTypes.arrayOf(React.PropTypes.any).isRequired,
  valueHandlers: React.PropTypes.arrayOf(React.PropTypes.func).isRequired,
  valueWidths: React.PropTypes.arrayOf(React.PropTypes.any).isRequired,
  valuePrefixes: React.PropTypes.arrayOf(React.PropTypes.any),
  formSpacing: React.PropTypes.any,
  listHandler: React.PropTypes.func
}
