context = window

@RateUserDialog = React.createClass({

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

  getInitialState: () ->
    {
    id: null,
    type: null,
    student: null,
    teacher: null,
    rating: null,
    }

  parseId: (id) ->
    if !id?
      {id: null, type: null}
    else
      bits = id.split('_')
      if bits.length == 2
        {id: bits[1], type: bits[0]}
      else
        {id: null, type: null}

  beforeShow: (args) ->
    logger.debug("RateUserDialog.beforeShow", args.d1)
    parsed = @parseId(args.d1)

    @setState({rating_decision: null, type: parsed.type, id: parsed.id, rating: null, willUpdate: false, description:''})

    as_student = parsed.type == 'teacher'
    rest.ratingDecision({
      as_student: as_student,
      teacher_id: parsed.id,
      student_id: parsed.id
    }).done((response) => @userLookupDone(response)).fail((jqXHR) => @userLookupFail(jqXHR))

  afterHide: () ->

  isRatingTeacher: () ->
    !@isRatingStudent()

  isRatingStudent: () ->
    @state.type == 'student'

  userLookupDone: (response) ->
    value = response.rating?.rating
    if value?
      @setState({rating: value, description: response.rating?.description})
    @setState({rating_decision: response})

  userLookupFail: (jqXHR) ->
    @app.ajaxError(jqXHR, null, null)

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

    @app.bindDialog('rate-user-dialog', dialogBindings);

  checkboxChanged: (e) ->
    $target = $(e.target)
    @setState({rating: $target.val()})

  componentDidMount: () ->
    @checkboxes = [{selector: 'input[name="rating"]', stateKey: 'rating'}]

    @root = $(@getDOMNode())

    @iCheckify()

  componentDidUpdate: () ->
    @iCheckify()

  descriptionChanged: (e) ->
    @setState({description: $(e.target).val()})

  doCancel: (e) ->
    e.preventDefault()
    @app.layout.cancelDialog('rate-user-dialog');

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

    if @disabled()
      return

    if @isRatingTeacher()
      data =
      {
        target_id: @state.id
        target_type: 'JamRuby::Teacher'
      }
    else
      data =
      {
        target_id: @state.id,
        target_type: 'JamRuby::User',
      }

    data.rating = @state.rating
    data.description = @state.description
    rest.createReview(data).done((response) => @createReviewDone(response)).fail((jqXHR) => @createReviewFail(jqXHR))

  createReviewDone: (response) ->
    if @isRatingTeacher()
      context.JK.Banner.showNotice("teacher rated", "Thank you for taking the time to provide your feedback.")
    else
      context.JK.Banner.showNotice("student rated", "Thank you for taking the time to provide your feedback.")

    @app.layout.closeDialog('rate-user-dialog')

  createReviewFail: (jqXHR) ->
    handled = false

    if jqXHR.status == 422
      response = JSON.parse(jqXHR.responseText)
      if response.errors.target?
        @app.layout.notify({title: "not allowed", text: "you can not rate someone until you have had a lesson with them"})
        handled = true

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

  disabled: () ->
    !@state.rating? || (!@state.rating_decision?)

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

    @setState({willUpdate: true})

  render: () ->
    submitClasses = classNames({'button-orange': true, disabled: @disabled()})
    if !@state.willUpdate && (@state.rating_decision? && @state.rating_decision.rating?)
      dialogContents = `<div className="dialog-inner">

        <h2>Would you like to update your rating/review of this teacher?</h2>

        <div className="actions">
          <a onClick={this.doCancel} className="button-grey">NO</a>
          <a onClick={this.willUpdate} className={submitClasses}>YES</a>
        </div>
      </div>`
    else
      if @isRatingTeacher()
        title = 'Rate Teacher'
        help = `<h2>Please rate this teacher based on your experience with them:</h2>`
        descriptionPrompt = `<h2>Please help other students by explaining what you like or don’t like about this teacher:</h2>`
        choices =
          `<div className="choices">
            <div className="field">
              <input type="radio" name="rating" value="5"/><label>Great teacher</label>
            </div>
            <div className="field">
              <input type="radio" name="rating" value="4"/><label>Good teacher</label>
            </div>
            <div className="field">
              <input type="radio" name="rating" value="3"/><label>Average teacher</label>
            </div>
            <div className="field">
              <input type="radio" name="rating" value="2"/><label>Poor teacher</label>
            </div>
            <div className="field">
              <input type="radio" name="rating" value="1"/><label>Terrible teacher</label>
            </div>
          </div>`
      else
        title = 'Rate Student'
        help = `<h2>Please rate this student based on your experience with them:</h2>`
        descriptionPrompt = `<h2>Please tell us if you have problems with this student in the form of tardiness, abusiveness, or other inappropriate behaviors. We will not share this information with other teachers or students, but we may use aggregate negative feedback on a student from multiple teachers to block the student from our lesson marketplace.</h2>`
        choices =
          `<div className="choices">
            <div className="field">
              <input type="radio" name="rating" value="5"/><label>Great student</label>
            </div>
            <div className="field">
              <input type="radio" name="rating" value="4"/><label>Good student</label>
            </div>
            <div className="field">
              <input type="radio" name="rating" value="3"/><label>Average student</label>
            </div>
            <div className="field">
              <input type="radio" name="rating" value="2"/><label>Poor student</label>
            </div>
            <div className="field">
              <input type="radio" name="rating" value="1"/><label>Terrible student</label>
            </div>
          </div>`
      dialogContents = `<div className="dialog-inner">

        {help}

        {choices}

        <div className="field description">
          {descriptionPrompt}
          <textarea name="description" placeholder="Enter a further bit of detail here" value={this.state.description}
                    onChange={this.descriptionChanged}></textarea>
        </div>

        <div className="actions">
          <a onClick={this.doCancel} className="button-grey">CANCEL</a>
          <a onClick={this.doRating} className={submitClasses}>SUBMIT RATING</a>
        </div>
      </div>`

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

        <h1>{title}</h1>
      </div>
      {dialogContents}
    </div>`

})