context = window
rest = context.JK.Rest()
logger = context.JK.logger
LocationActions = context.LocationActions
UserStore = context.UserStore

@Subscription = React.createClass({


  mixins: [Reflux.listenTo(@LocationStore, "onLocationsChanged")]


  getInitialState: () ->
    {
    clicked: false,
    selectedCountry: null,
    selectedPlan: null,
    subscription: null
    }

  onLocationsChanged: (countries) ->
    console.log("countries in ", countries)
    @setState({countries: countries})

  onCountryChanged: (e) ->
    val = $(e.target).val()
    @setState({selectedCountry: val})

  currentCountry: () ->
    this.state.selectedCountry || this.props.selectedCountry || ''

  onPlanChanged: (e) ->
    val = $(e.target).val()
    @setState({selectedPlan: val})

  currentPlan: () ->
    this.state.selectedPlan || this.props.selectedPlan || ''

  openBrowser: () ->
    context.JK.popExternalLink("https://www.jamkazam.com/client#/subscription")

  onRecurlyToken: (err, token_data) ->

    if err
      console.log("error", err)
      # handle error using err.code and err.fields
    else
      # recurly.js has filled in the 'token' field, so now we can submit the
      # form to your server
      console.log("eintercepted", token_data)
      rest.createSubscription({plan_code: @state.selectedPlan, recurly_token: token_data.id})

  onFormSubmit: (event) ->
    form = event.target
    console.log("ok work this", form)
    event.preventDefault()
    recurly.token(@elements, form, @onRecurlyToken)

  configureRecurly: () =>
    unless window.configuredRecurly
      window.recurly.configure(gon.global.recurly_public_api_key)
      window.configuredRecurly = true


  componentDidMount: () ->
    LocationActions.load()

    @configureRecurly()

    @elements = recurly.Elements()
    cardElement = @elements.CardElement(
      inputType: 'mobileSelect',
      style: {
        fontSize: '1em',
        lineHeight: '42px',
        placeholder: {
          color: 'gray !important',
          fontWeight: 'bold',
          content: {
            number: 'Card number',
            cvv: 'CVC'
          }
        },
        backgroundColor: 'white'
        invalid: {
          fontColor: 'red'
        }
      }
    )
    console.log("attaching", $('#subscription-elements'))
    cardElement.attach('#subscription-elements')

    @root = $(@getDOMNode())

    document.querySelector('#subscription-form').addEventListener('submit', @onFormSubmit.bind(this))


  defaultText: () ->
    'Select Country'

  render: () ->

    if @state.countries?
      countries = [`<option key="" value="">{this.defaultText()}</option>`]
      for countryId, countryInfo of @state.countries
        countries.push(`<option key={countryId} value={countryId}>{countryInfo.name}</option>`)

      country = @state.countries[this.currentCountry()]
    else
      countries = []

    countryJsx = `
        <select name="countries" onChange={this.onCountryChanged} value={this.currentCountry()} data-recurly="country" autocomplete="shipping country">{countries}</select>`

    plan_codes = [`<option key='' value='' >Select Plan</option>`]
    for plan in gon.global.subscription_codes
      plan_codes.push(`<option key={plan.id} value={plan.id}>{plan.name} ({plan.price}/month)</option>`)

    plansJsx = `
      <select name="plan_code" onChange={this.onPlanChanged} value={this.currentPlan()} >{plan_codes}</select>`

    `<div>
        <h3>Update Payment</h3>
        <form id="subscription-form">
        <div id="subscription-account-data">
            <label for="first_name">First Name:</label>
            <input type="text" data-recurly="first_name" required autocomplete="cc-give-name"></input>

            <label for="last_name">Last Name:</label>
            <input type="text" data-recurly="last_name" required autocomplete="cc-family-name"></input>

            <label for="address1">Address 1:</label>
            <input type="text" data-recurly="address1" required autocomplete="shipping address-line1"></input>

            <label for="address2">Address 2:</label>
            <input type="text" data-recurly="address2" required autocomplete="shipping address-line2"></input>

            <label for="city">City:</label>
            <input type="text" data-recurly="city" required autocomplete="shipping address-level2"></input>

            <label for="state">State:</label>
            <input type="text" data-recurly="state" required autocomplete="shipping address-level1"></input>

            <label for="postal_code">Postal Code:</label>
            <input type="text" data-recurly="postal_code" autocomplete="shipping postal-code"></input>

            <label for="country">Country:</label>
            {countryJsx}

            <label for="plan_code">Plan:</label>
            {plansJsx}
        </div>
        <div id="subscription-elements-legacy">
        </div>

        <input type="hidden" name="recurly-token" data-recurly="token"></input>

        <button className="button-orange">SUBMIT</button>
    </form>
    </div>`

})