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

@SchoolTeacherListPage = React.createClass({

  signupUrl: () ->
    "/school/#{this.props.school.id}/student?redirect-to=#{encodeURIComponent(window.location.href)}"

  render: () ->
    loggedIn = context.JK.currentUserId?

    if this.props.school.large_photo_url?
      logo = `<div className="school-logo">
        <img src={this.props.school.large_photo_url}/>
      </div>`

    if this.state.done
      ctaButtonText = 'reloading page...'
    else if this.state.processing
      ctaButtonText = 'hold on...'
    else
      if loggedIn
        ctaButtonText = "SIGN UP"
      else
        ctaButtonText = "SIGN UP"

    if loggedIn
      register = `<div className={classNames({'cta-button' : true})}>ALREADY SIGNED UP</div>`
    else
      if this.state.loginErrors?
        for key, value of this.state.loginErrors
          break

        errorText = context.JK.getFullFirstError(key, this.state.loginErrors,
          {email: 'Email', password: 'Password', 'terms_of_service': 'The terms of service'})

      register = `<div className="register-area jam-class">
        <div className={classNames({'errors': true, 'active': this.state.loginErrors})}>
          {errorText}
        </div>
        <form className="school-signup-form">
          <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"/>
          <button className={classNames({'cta-button' : true, 'processing': this.state.processing})}
                  onClick={this.ctaClick}>{ctaButtonText}</button>
        </form>
      </div>`


    `<div className="container">
      <div className="header-area">
        <div className="header-content">
          {logo}

          <div className="headers">
            <h1>OUR TEACHERS</h1>

            <h2>at {this.props.school.name}</h2>
          </div>
          <div className="explain">
            <p>
              If you have not signed up to take private music lessons online using JamKazam, you can sign up using the form
              on the right side of the page.
            </p>

            <p>
              If you have already signed up and have set up your gear with help from the people at JamKazam, then you are
              ready to book your lessons with a teacher.
              You may book a lesson with one of your school's preferred instructors from the list below by clicking the BOOK
              LESSON button next to your preferred instructor.
            </p>

            <p>
              If your school does not have preferred instructors, or if your music program director has indicated that you
              should find
              and select your instructor from our broader community of teachers, then <a href='/client#/'>click this link</a> to use
              our instructor search feature to find
              a great instructor for you. If you need help, email us at <a href='mailto:support@jamkazam.com'>support@jamkazam.com</a>.
            </p>
          </div>


          <br className="clearall"/>
        </div>
      </div>

      <div className="preview-and-action-box jamclass school">

        <div className="preview-jamtrack-header">
          Sign Up For Lessons
        </div>
        <div className={classNames({'preview-area': true, 'jam-class': true})}>
          <p>Sign up to let us know you’re interested taking lessons online using JamKazam.</p>
          <p>We'll follow up to answer all your questions, and to help you get set up and ready to go.</p>

          <p>We will not share your email. See our <a href="/corp/privacy" onClick={this.privacyPolicy}>privacy
            policy</a></p>
          {register}
        </div>
      </div>
      <div className="teacher-lister">

        {this.list()}
      </div>
      <br className="clearall"/>
      <br/>
    </div>`

  teaches: (teacher) ->
    if teacher.instruments.length == 0
      return ''
    else if teacher.instruments.length == 2
      return 'teaches ' + teacher.instruments[0].description + ' and ' + teacher.instruments[1].description
    else
      return 'teaches ' + teacher.instruments.map((i) -> i.description).join(', ')

  list: () ->
    teachers = []

    teachersList = this.rabl.teachers
    for teacher in teachersList

      continue if !teacher.user?

      teachers.push(`
        <div className="school-teacher">
          <div className="school-top-row">
            <div className="school-left">
              <div className="avatar">
                <span className="vertalign">
                  <img src={teacher.user.resolved_photo_url}/>
                </span>
              </div>
              <div className="book-lesson">
                <span className="vertalign">
                  <a className="button-orange" onClick={this.bookLessonClicked.bind(this, teacher)} href={this.bookLessonUrl(teacher)}>BOOK LESSON</a>
                </span>
              </div>
            </div>
            <div className="school-right">
            <div className="username">
            <span className="vertalign">
              <span className="teacher-descr">
                {teacher.user.name} {this.teaches(teacher)}
                <a className="profile-link" href={teacher.user.teacher_profile_url}>see {teacher.user.first_name}'s detailed instructor profile</a>
              </span>
            </span>
            </div>
              </div>

            <br className="clearall"/>
          </div>
        </div>`)

    teachers

  bookLessonClicked: (teacher, e) ->
    loggedIn = context.JK.currentUserId?

    if loggedIn
      # do nothing
    else
      e.preventDefault()
      context.JK.Banner.showNotice('Please Sign Up', 'Before booking a lesson with a teacher, please sign up by filling out the sign up form on the right. Thank you!')

  bookLessonUrl: (teacher) ->
    '/client#/jamclass/book-lesson/normal_' + teacher.user.id

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

  componentWillMount: () ->
    this.rabl = JSON.parse(this.props.rabl)
  componentDidMount: () ->
    $root = $(this.getDOMNode())
    $checkbox = $root.find('.terms-checkbox')
    context.JK.checkbox($checkbox)

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

    return if @state.processing

    @setState({loginErrors: null})

    loggedIn = context.JK.currentUserId?

    if loggedIn
      #window.location.href = "/client#/jamclass"
      window.location.href = "/client#/profile/#{context.JK.currentUserId}"
    else
      @createUser()

    @setState({processing: true})

  createUser: () ->
    $form = $('.school-signup-form')
    email = $form.find('input[name="email"]').val()
    password = $form.find('input[name="password"]').val()
    terms = $form.find('input[name="terms"]').is(':checked')

    rest.signup({
      email: email,
      password: password,
      first_name: null,
      last_name: null,
      terms: terms,
      student: true,
      school_id: this.props.school.id
    })
    .done((response) =>
      @setState({done: true})
      #window.location.href = "/client#/jamclass"
      window.location.reload()
    ).fail((jqXHR) =>
      @setState({processing: false})
      if jqXHR.status == 422
        response = JSON.parse(jqXHR.responseText)
        if response.errors
          @setState({loginErrors: response.errors})
        else
          context.JK.app.notify({title: 'Unknown Signup Error', text: jqXHR.responseText})
      else
        context.JK.app.notifyServerError(jqXHR, "Unable to Sign Up")
    )
})