context = window
rest = context.JK.Rest()

@PosaActivationPage = React.createClass({

  render: () ->
    if this.props.retailer.large_photo_url?
      logoImg = `<img src={this.props.retailer.large_photo_url}/>`
    logo = `<div className="retailer-logo">
      {logoImg}
      <div className="retailer-name">
        {this.props.retailer.name}
        </div>
      <br className="clearall"/>
    </div>`

    ctaButtonText = 'ACTIVATE'
    if @state.processing
      ctaButtonText = 'HOLD ON'

    console.log("this.props.retailer", this.props.retailer, this.props.has_teachers)
    if this.state.loginErrors?
      for key, value of this.state.loginErrors
        break
    if this.state.emailErrors?
      for errorKey, value of this.state.emailErrors
        break

    success = `<div className="success-message">
      {this.state.success}
    </div>`

    emailSuccess = `<div className="success-message">
      {this.state.emailSuccess}
    </div>`

    posaErrors = context.JK.getFullFirstError(key, this.state.loginErrors,
      {code: 'This code', activated_at: 'This code', claimed_at: 'Claimed', user: 'User', retailer: 'Retailer'})
    emailErrors = context.JK.getFullFirstError(errorKey, this.state.emailErrors,
      {email: 'Email address', retailer: 'Retailer'})

    register = `<div className="register-area jam-class">
      <form className="retailer-signup-form" onSubmit={this.submit}>
        <div className="field">
          <label>POSA Card Code: </label><input type="text" name="code"/>
        </div>
        <a
          className={classNames({'activate-btn': true, 'button-orange':true, 'cta-button' : true, 'processing': this.state.processing})}
          onClick={this.activateClick}>{'ACTIVATE'}</a>
      </form>
      {success}
      <div className={classNames({'errors': true, 'active': this.state.loginErrors})}>
        {posaErrors}
      </div>
    </div>`

    sendEmail = `<div className="send-email jam-class">
      <form className="retailer-email-form" onSubmit={this.submitEmail}>
        <div className="field">
          <label>Customer Email: </label><input type="text" name="email"/>
        </div>
        <a
          className={classNames({'activate-btn': true, 'button-orange':true, 'cta-button' : true, 'processing': this.state.processing})}
          onClick={this.submitEmail}>{'SEND LINKS'}</a>
      </form>
      {emailSuccess}
      <div className={classNames({'errors': true, 'active': this.state.emailErrors})}>
        {emailErrors}
      </div>
    </div>`

    leftColumnClasses = classNames({column: true, has_teachers: this.props.has_teachers})
    rightColumnClasses = classNames({column: true, has_teachers: this.props.has_teachers})

    `<div className="container">
      <div className={leftColumnClasses}>
        <div className="header-area">
          <div className="header-content">
            {logo}
            <div className="headers">
              <h1>ACTIVATE JAMKAZAM POSA CARD</h1>
            </div>
            <br className="clearall"/>
          </div>
        </div>

        <div className="explain">
          <p>
            Please enter the 10-digit code from the back of the POSA card you have sold, and then click the Activate
            Card button:
          </p>
        </div>

        {register}
      </div>
      <div className={rightColumnClasses}>
        <div className="header-area">
          <div className="header-content">

            <div className="headers">
              <h1>SEND TEACHER LINKS TO STUDENT</h1>
            </div>
            <br className="clearall"/>
          </div>
        </div>

        <div className="explain">
          <p>
            If you want to send links to your store’s teachers to thfcustomer, enter their email address below, and click the Send Links button.
          </p>
        </div>

        {sendEmail}
      </div>
      <div className="clearall"/>

    </div>`

  submit: (e) ->
    @activateClick(e)

  getInitialState: () ->
    {loginErrors: null, processing: false, emailErrors: null}

  componentDidMount: () ->

    # add item to cart, create the user if necessary, and then place the order to get the free JamTrack.
  activateClick: (e) ->
    e.preventDefault()

    return if @state.processing

    @setState({processing: true, success: null, emailSuccess:null, loginErrors: null})

    @activateCode()

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

    return if @state.processing

    $form = $('.retailer-email-form')
    email = $form.find('input[name="email"]').val()

    emailErrors = null
    if(!email)
      emailErrors = {"email": ['must be specified']}
      processing = false
    else

      processing = true
      rest.sendRetailerCustomerEmail({retailer: this.props.retailer.id, email: email})
      .done((response) =>
        @setState({processing: false, emailSuccess: "List of teachers sent to #{email}."})
        $form.find('input[name="email"]').val('')
      )
      .fail((jqXHR) =>
        @setState({processing: false})

        if jqXHR.status == 404
          @setState({emailErrors: {"retailer": ['is not valid']}})
        else if jqXHR.status == 422
          response = JSON.parse(jqXHR.responseText)
          if response.errors
            @setState({emailErrors: response.errors})
          else
            context.JK.app.notify({title: 'Unable to Send Email', text: jqXHR.responseText})
        else
          context.JK.app.notifyServerError(jqXHR, "Unable to Send Email")
      )

    @setState({processing: processing, success: null, emailSuccess: null, emailErrors: emailErrors})


  activateCode: () ->
    $form = $('.retailer-signup-form')
    code = $form.find('input[name="code"]').val()

    rest.posaActivate({
      code: code,
      slug: @props.retailer.slug
    })
    .done((response) =>
      @setState({processing: false, success: 'Card successfully activated. Please give card to customer. Thank you!'})
    ).fail((jqXHR) =>
      @setState({processing: false})

      console.log("jqXHR.status", jqXHR.status)
      if jqXHR.status == 404
        @setState({loginErrors: {"code": ['is invalid. Please try entering the code again. If it still will not work, try a different card, and please email us at support@jamkazam.com so we can resolve the problem with this card.']}})
      else if jqXHR.status == 422
        response = JSON.parse(jqXHR.responseText)
        if response.errors
          @setState({loginErrors: response.errors})
        else
          context.JK.app.notify({title: 'Unable to Activate POSA Card', text: jqXHR.responseText})
      else
        context.JK.app.notifyServerError(jqXHR, "Unable to Activate POSA Card")
    )
})