context = window
rest = context.JK.Rest()
ReactCSSTransitionGroup = React.addons.CSSTransitionGroup;

badCode = 'This is not a valid code. Please carefully re-enter the code and try again. If it still does not work, please email us at support@jamkazam.com to report this problem.'
@AccountActivatePage = React.createClass({

  render: () ->


    if this.state.formErrors?
      for key, value of this.state.formErrors
        break

      errorText = context.JK.getFullFirstError(key, @state.formErrors, {email: 'Email', password: 'Password', gift_card: 'Coupon Code', posa_cards: 'Coupon Code', 'terms_of_service' : 'The terms of service', claimed_at: "Last coupon code used"})

      if errorText? && errorText.indexOf('does not exist') > -1
        errorText = 'This is not a valid code. Please carefully re-enter the code and try again. If it still does not work, please email us at support@jamkazam.com to report this problem.'

      if errorText? && errorText.indexOf('must already be set') > -1
        errorText = 'This card has not been activated by a retailer and cannot currently be used. If you purchased this card from a store, please return to the store and have the store activate the card. Only the store where you purchased this card can activate it.'

      if errorText? && errorText.indexOf('already claimed') > -1
        errorText = 'This card has already been claimed.  If you believe this is in error, please email us at support@jamkazam.com to report this problem.'

    buttonClassnames = classNames({'redeem-giftcard': true, 'button-orange': true, disabled: @state.processing || @state.done })


    if @state.done
      if this.state.gifted_jamtracks

        button =
          `<div key="done" className="done-action">
            <div>You now have {this.state.gifted_jamtracks} JamTracks credits on your account!</div>
            <div><a className="go-browse" href="/client#/jamtrack">go to JamTracks home page</a></div>
          </div>`
      else
        if this.state.purchase_required
          button =
            `<div key="done" className="done-action jam-class purchase-needed">
              <div>You have claimed <span className="amount-gifted">{this.state.jamclass_credits}</span> 30-minute JamClass credits, but still need to enter your credit card info!</div>
              <div><a className="go-browse" href="/client#/jamclass/lesson-payment/test-drive">go to the lesson payment page</a></div>
            </div>`
        else
          button =
            `<div key="done" className="done-action jam-class all-done">
              <div>You now have <span className="amount-gifted">{this.state.jamclass_credits}</span> 30-minute JamClass credits on your account!</div>
              <div><a className="go-browse" href="/client#/jamclass/searchOptions">go to JamClass teacher search page</a></div>
            </div>`
    else
      if context.JK.currentUserId?
        if @state.processing
          buttonText = 'ACTIVATING COUPON CODE...'
        else
          buttonText = 'ACTIVATE COUPON CODE'
      else
        if @state.processing
          buttonText = 'ACTIVATING ACCOUNT...'
        else
          buttonText = 'ACTIVATE ACCOUNT'

      button = `<button  key="button" className={buttonClassnames} onClick={this.action}>{buttonText}</button>`

    action = `<ReactCSSTransitionGroup transitionName="session-track-list">
            {button}
            </ReactCSSTransitionGroup>`

    title = 'Activate Account'

    if context.JK.currentUserId?
      form =
        `<form onSubmit={this.submit}>
          <label>Coupon Code:</label><input type="text" name="code"/>
          {action}
        </form>`
      instruments = `<p className="instructions">Enter the 10-digit code you received in your email and click the Activate button below.</p>`
    else
      form =
        `<form onSubmit={this.submit}>
          <label>Coupon Code:</label><input type="text" name="code"/>
          <label>Email:</label><input type="text" name="email"/>
          <label>Password:</label><input type="password" name="password"/>
          <div className="clearall"/>
          <input className="terms-checkbox" type="checkbox" name="terms" /><label className="terms-help">I have read and agree to the JamKazam <a href="/corp/terms" onClick={this.termsClicked}>terms of service</a></label>
          <div className="clearall"/>
          {action}
        </form>`
      instruments = `<p className="instructions">Enter the 10-digit code you received in your email and click the Activate button below.</p>`


    classes = classNames({'redeem-container': true, 'not-logged-in': !context.JK.currentUserId?, 'logged-in': context.JK.currentUserId? })
    `<div className={classes}>
      <div className="redeem-content">
        <h2>{title}</h2>
        {instruments}
        {form}
        <div className={classNames({'errors': true, 'active': this.state.formErrors})}>
          {errorText}
        </div>
      </div>
    </div>`

  getInitialState: () ->
    {formErrors: null, processing:false, gifted_jamtracks: null, jamclass_credits: null, purchase_required: null}

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

    context.JK.popExternalLink('/corp/privacy')

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

    context.JK.popExternalLink('/corp/terms')

  componentDidMount:() ->
    $root = $(this.getDOMNode())
    $checkbox = $root.find('.terms-checkbox')
    console.log("$checkbox", $checkbox)
    context.JK.checkbox($checkbox)

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

    if @state.done || @state.processing
      e.preventDefault()
      return

    if context.JK.currentUserId?
      @redeem(e)
    else
      @signup(e)

  redeem: (e) ->
    e.preventDefault()
    return if @state.done || @state.processing

    $root = $(@getDOMNode())
    $code = $root.find('input[name="code"]')
    code = $code.val()


    @setState({processing:true})

    rest.redeemGiftCard({gift_card: code})
    .done((response) =>

      @setState({formErrors: null, processing:false, done: true, gifted_jamtracks: response.gifted_jamtracks, jamclass_credits: response.jamclass_credits, purchase_required: response.purchase_required})

    ).fail((jqXHR) =>
      @setState({processing:false})

      if jqXHR.status == 422
        response = JSON.parse(jqXHR.responseText)
        if response.errors
          @setState({formErrors: response.errors})
        else
          context.JK.app.notify({title: 'Unknown Error', text: jqXHR.responseText})
      else
        context.JK.app.notifyServerError(jqXHR, "Unable to Apply Coupon")
    )

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

    return if @state.done || @state.processing

    $root = $(@getDOMNode())
    $email = $root.find('input[name="email"]')
    $code = $root.find('input[name="code"]')
    $password = $root.find('input[name="password"]')
    terms = $root.find('input[name="terms"]').is(':checked')

    @setState({processing:true})
    email = $email.val()
    password = $password.val()
    code = $code.val()
    if !code
      # must pass up non-null value to indicate user is trying to redeem giftcard while creating account
      code = ''

    rest.signup({email: email, password: password, gift_card: code, terms: terms})
    .done((response) =>

      @setState({formErrors: null, processing:false, done: true, gifted_jamtracks: response.gifted_jamtracks, jamclass_credits: response.jamclass_credits, purchase_required: response.purchase_required})

    ).fail((jqXHR) =>
      @setState({processing:false})

      if jqXHR.status == 422
        response = JSON.parse(jqXHR.responseText)
        if response.errors
          @setState({formErrors: response.errors})
        else
          context.JK.app.notify({title: 'Unknown Signup Error', text: jqXHR.responseText})
      else
        context.JK.app.notifyServerError(jqXHR, "Unable to Sign Up")
    )
})