import React from 'react'

class SMS extends React.Component {
  constructor() {
    super()
    this.handleChange = this.handleChange.bind(this)
    this.addRecipient = this.addRecipient.bind(this)
    this.submitForm = this.submitForm.bind(this)
  }

  handleChange (event) {
    event.preventDefault()
    const { changeForm } = this.props.smsActions
    changeForm({
      sender: this.sender.value,
      body: this.body.value,
      newRecipient: this.newRecipient.value
    })
  }

  submitForm (event) {
    event.preventDefault()
    const { sendSMSRequest } = this.props.smsActions
    const state = this.props.sms
    sendSMSRequest(state)
  }

  addRecipient (event) {
    event.preventDefault()
    const { addRecipient } = this.props.smsActions
    addRecipient(this.newRecipient.value)
  }

  render () {
    const state = this.props.sms
    const actions = this.props.smsActions
    const { sender, body, newRecipient } = state

    return (
      <div>
        <h2>SMS</h2>
        <form>
          <label htmlFor="sender">Sender Name</label>
          <input type="input" id="sender" ref={(input => {this.sender = input})} value={sender} placeholder="Sender Name" onChange={this.handleChange}/>
          <br />
          <label htmlFor="body">Nachricht</label>
          <textarea id="body" ref={(input => {this.body = input})} value={body} placeholder="Nachricht" onChange={this.handleChange} />
          <br />
          <label htmlFor="newRecipient">Neuer Empfaenger</label>
          <input type="input" id="newRecipient" ref={(input => {this.newRecipient = input})} value={newRecipient} placeholder="Neuer Empfaenger" onChange={this.handleChange}/>
          <input type="button" value="ok" onClick={this.addRecipient}/>
          <br />
          <input type="submit" value="Senden" onClick={this.submitForm}/>
        </form>
        <h3>Nachricht</h3>
        <pre>{JSON.stringify(state.message, null, 2)}</pre>
        <h3>Alle Empfaenger</h3>
        <ul>
          {state.recipients.map((recipient, key) => 
          <li key={key}>{(typeof recipient === 'string') ? recipient : `${recipient.fullName} (${recipient.phone ? recipient.phone : 'keine Nummer'})`}</li>
          )}
        </ul>
      </div>
    )
  }
}

export default SMS
