context = window
RetailerStore = context.RetailerStore

@InviteRetailerUserDialog = React.createClass({

  mixins: [Reflux.listenTo(@AppStore, "onAppInit"), Reflux.listenTo(RetailerStore, "onRetailerChanged")]
  teacher: false

  beforeShow: (args) ->
    logger.debug("InviteRetailerUserDialog.beforeShow", args.d1)
    @firstName = ''
    @lastName = ''
    @email = ''

    @setState({inviteErrors: null, teacher: args.d1})
  afterHide: () ->

  onRetailerChanged: (retailerState) ->
    @setState(retailerState)

  onAppInit: (@app) ->
    dialogBindings = {
      'beforeShow': @beforeShow,
      'afterHide': @afterHide
    };

    @app.bindDialog('invite-retailer-user', dialogBindings);

  componentDidMount: () ->
    @root = $(@getDOMNode())

  getInitialState: () ->
    {inviteErrors: null, retailer: null, sending: false}

  doCancel: (e) ->
    e.preventDefault()
    @app.layout.closeDialog('invite-retailer-user', true);

  doInvite: (e) ->
    e.preventDefault()

    if this.state.sending
      console.log("sending already")
      return


    email = @root.find('input[name="email"]').val()
    lastName = @root.find('input[name="last_name"]').val()
    firstName = @root.find('input[name="first_name"]').val()
    retailer = context.RetailerStore.getState().retailer
    @setState({inviteErrors: null, sending: true})
    rest.createRetailerInvitation({
      id: retailer.id,
      as_teacher: this.state.teacher,
      email: email,
      last_name: lastName,
      first_name: firstName
    }).done((response) => @createDone(response)).fail((jqXHR) => @createFail(jqXHR))

  createDone: (response) ->
    console.log("invitation added", response)
    @setState({inviteErrors:null, sending: false})
    context.RetailerActions.addInvitation(this.state.teacher, response)
    context.JK.Banner.showNotice("invitation sent", "Your invitation has been sent!")
    @app.layout.closeDialog('invite-retailer-user')

  createFail: (jqXHR) ->
    handled = false

    if jqXHR.status == 422
      errors = JSON.parse(jqXHR.responseText)
      @setState({inviteErrors: errors, sending: false})
      handled = true

    if !handled
      @app.ajaxError(jqXHR, null, null)


  close: (e) ->
    e.preventDefault()
    @app.layout.closeDialog('invite-retailer-user');


  renderRetailer: () ->
    firstNameErrors = context.JK.reactSingleFieldErrors('first_name', @state.inviteErrors)
    lastNameErrors = context.JK.reactSingleFieldErrors('last_name', @state.inviteErrors)
    emailErrors = context.JK.reactSingleFieldErrors('email', @state.inviteErrors)

    firstNameClasses = classNames({first_name: true, error: firstNameErrors?, field: true})
    lastNameClasses = classNames({last_name: true, error: lastNameErrors?, field: true})
    emailClasses = classNames({email: true, error: emailErrors?, field: true})
    sendInvitationClasses = classNames({'button-orange': true, disabled: this.state.sending})

    if @state.teacher
      title = 'invite teacher'
      help = `<p>Send invitations to teachers who teach through your music store. When your teachers accept this invitation to create teacher accounts on JamKazam, you can easily send emails to customers who purchase online lessons pointing these customers to your preferred teachers from your store. </p>`
    else
      title = 'invite student'
      help = `<p>
        Shouldn't be here...
      </p>`

    `<div>
      <div className="content-head">
        <img className="content-icon" src="/assets/content/icon_add.png" height={19} width={19}/>

        <h1>{title}</h1>
      </div>
      <div className="dialog-inner">

        {help}

        <div className={firstNameClasses}>
          <label>First Name: </label>
          <input type="text" defaultValue={this.firstName} name="first_name"/>
          {firstNameErrors}
        </div>

        <div className={lastNameClasses}>
          <label>Last Name: </label>
          <input type="text" defaultValue={this.lastName} name="last_name"/>
          {lastNameErrors}
        </div>

        <div className={emailClasses}>
          <label>Email Name: </label>
          <input type="text" defaultValue={this.email} name="email"/>
          {emailErrors}
        </div>

        <div className="actions">
          <a onClick={this.doCancel} className="button-grey">CANCEL</a>
          <a onClick={this.doInvite} className={sendInvitationClasses}>SEND INVITATION</a>
        </div>
      </div>
    </div>`

  render: () ->
    retailer = this.state.retailer

    if !retailer?
      return `<div>no retailer</div>`

    @renderRetailer()


})