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()
    this.props.smsActions.changeForm({
      sender: this.sender.value,
      body: this.body.value,
      newRecipient: this.newRecipient.value
    })
  }

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

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

  removeRecipient (key, event) {
    event.preventDefault()
    this.props.smsActions.removeRecipient(key)
  }

  setRecipients (value, event) {
    event.preventDefault()
    this.props.smsActions.setRecipients(value)
  }

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

    return (
      <div>
        <h2>SMS</h2>
        <p>Guthaben: {state.credit}</p>
        <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} />
          <p>{body.length}/160 Zeichen</p>
          <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>Alle Empfaenger</h3>
        <p>{state.recipients.filter(recipient => (typeof recipient === 'string') || recipient.phone).length} von {state.recipients.length} mit Telefonnummer</p>
        {state.recipients.length ? <p><a onClick={(event) => {this.setRecipients([], event)}}>{'\u2716'}</a> Alle löschen</p> : null}
        <ul>
          {state.recipients.map((recipient, key) => 
          <li key={key}><a onClick={(event) => {this.removeRecipient(key, event)}}>{'\u2716'}</a> {(typeof recipient === 'string') ? recipient : `${recipient.fullName} (${recipient.phone ? recipient.phone : 'keine Nummer'})`}</li>
          )}
        </ul>
      </div>
    )
  }
}

export default SMS
