var React = require("react/addons"),
    UserRegistration = require('../../models/userRegistration'),
    RibicaValidationMixin = require('../../components/shared/mixins/ribicaValidationMixin'),
    UserStore = require('../../stores/userStore'),
    NavigationActions = require('../../actions/navigationActions'),
   UserActions = require('../../actions/userActions'),
   ValidationUtils = require('../../utils/validation');



var Register = React.createClass({
  mixins: [React.addons.LinkedStateMixin, RibicaValidationMixin],
  getInitialState: function() {
    return {
      myBabyDetailsVisible: false,
      firstName: '',
      lastName: '',
      email: '',
      password: '',
      passwordConfirmation: '',
      registration: UserStore.getRegistrationState(),
      myBabyDOBDay: -1,
      myBabyDOBMonth: -1,
      myBabyDOBYear: -1,
      myBabyOnTheWay: true,
      loginState : UserStore.getLoginState()
    };
  },
  myBabyChange: function(e) {
    this.setState({
      myBabyDetailsVisible: true,
      myBabyOnTheWay: (e.currentTarget.value === "1" ? true: false)
    });
  },
  onKeyPress: function(e) {
      var enterKeyCode = 13;
      if(e.which == enterKeyCode) {
          this.doRegister();
      }
  },
  renderMonthSelector: function() {
    var months = ['Januar', 'Februar', 'Mart', 'April', 'Maj', 'Juni',
    'Juli','August','Septembar', 'Oktobar','Novembar','Decembar'];

    var monthsSelect = [<option value='-1'>Mjesec</option>];
    for(var i = 1; i <= months.length; i++) {
      monthsSelect.push(<option value={i}>{months[i - 1]}</option>)
    }

    return (<select  className="form-control " onChange={this.onBabyDOBMonthChange}>{monthsSelect}</select>)
  },
  renderYearSelector: function() {
    var currentYear = (new Date().getFullYear());
    var years = [];
    years.push(<option value='-1'>Godina</option>)

    for(var i = 0; i < 12; i++) {
      years.push(<option value={currentYear - i}>{currentYear - i}</option>)
    }

    return (<select  className="form-control " onChange={this.onBabyDOBYearChange}> {years} </select>)
  },
  renderDaySelector: function() {
    var days = [];
    days.push(<option value='-1'>Dan</option>)
    for(var i = 1; i <= 31; i++) {
      days.push(<option value={i}>{i}</option>)
    }

    return (<select className="form-control " onChange={this.onBabyDOBDayChange}> {days} </select>)
  },
  onBabyDOBDayChange: function(e) {
      this.setState({
          myBabyDOBDay: e.currentTarget.value
      });
  },
  onBabyDOBMonthChange: function(e) {
      this.setState({
          myBabyDOBMonth: e.currentTarget.value
      });
  },
  onBabyDOBYearChange: function(e) {
      this.setState({
          myBabyDOBYear: e.currentTarget.value
      });
  },
  myBabyNameChange: function(e) {
      this.setState({
          babyName: e.currentTarget.value
      });
  },
  myBabyGenderChange: function(e) {
      this.setState({
          babyGender: e.currentTarget.value
      });
  },

  validations: {
    firstName: function(value) {
      if (!ValidationUtils.isValidRequired(value)) {
        return ["Ime je obavezno."];
      }
    },
    password: function(value, callback) {
      if(!ValidationUtils.isValidRequired(value)) {
        return ["Šifra je obavezna."];
      }

      if (value.length < 6) {
        return ["Šifra mora sadržavati minimalno 6 karaktera."]
      }

      if (callback) {
        callback([], ["passwordConfirmation"]);
      }
    },
    passwordConfirmation: function(value) {
      if (this.getState().password !== value) {
        return ["Šifre se ne podudaraju."];
      }
    },
    lastName : function(value) {
      if (!ValidationUtils.isValidRequired(value)) {
        return ["Prezime je obavezno."];
      }
    },
    _emailTimeoutId: null,
    email: function(value, callback) {

      if (ValidationUtils.isValidEmail(value)) {
        //clearTimeout(this._emailTimeoutId);
        //this._emailTimeoutId = setTimeout(function(){

          //// TODO: check if email exists
          //if (value === 'edin@edin.com') {
            //if(callback) {
              //var errors= ['Email is already taken'];
              //callback(errors);
            //}
          //} else {
            //if(callback) {
              //callback([]);
            //}
          //}

        //}.bind(this), 1000);
      } else {
        return ['Neispravna email adresa.'];
      }
    }
  },
  renderGenderImage: function() {
      if(this.state.babyGender === "boy") {
        return <img id="imgImage" name="imgImage" src="https://res.cloudinary.com/du5pdibul/image/upload/v1428813559/baby-blue_trmmbp.png" alt="baby" />
      } else if (this.state.babyGender === "girl") {
        return <img id="imgImage" name="imgImage" src="https://res.cloudinary.com/du5pdibul/image/upload/v1428813559/baby-pink_j0eis4.png" alt="baby" />
      }

      return <img id="imgImage" name="imgImage" src="https://res.cloudinary.com/du5pdibul/image/upload/v1428813559/baby-gray_mijkax.png" alt="baby" />
  },
  renderErrorMessage: function(message){
    return (<div className='error-message'>{message}</div>)
  },
  componentDidMount: function() {
      UserStore.addChangeListener(this.onUserStoreChange);
  },
  componentWillUnmount: function() {
      UserStore.removeChangeListener(this.onUserStoreChange);
  },
  onUserStoreChange: function() {
      this.setState({
          registration: UserStore.getRegistrationState(),
          loginState : UserStore.getLoginState()
      });
  },
  onRegisterClick: function(e) {
    this.doRegister();
    e.preventDefault();
  },
  doRegister: function() {
    if(this.validate()) {
      var children = [];
      if (this.state.myBabyDetailsVisible) {

          var dobOk = this.state.myBabyDOBDay !== -1 && this.state.myBabyDOBMonth !== -1 && this.state.myBabyDOBYear !== -1;

          if (dobOk || this.state.babyName !== undefined || this.state.babyGender !== undefined) {
              var childInfo = {
                  name: this.state.babyName,
                  gender: this.state.babyGender === "boy" ? 1 : 2,
                  on_the_way: this.state.myBabyOnTheWay
              }

              if(dobOk) {
                  var dob = this.state.myBabyDOBDay + '/' + this.state.myBabyDOBMonth + '/' + this.state.myBabyDOBYear;
                  childInfo.date_of_birth = dob;
              }
              children.push(childInfo);
          }
      }

      var user = new UserRegistration({
        first_name: this.state.firstName,
        last_name: this.state.lastName,
        email: this.state.email,
        password: this.state.password,
        password_confirmation: this.state.passwordConfirmation,
        children_attributes : children

      });

      // need to add info about child


      UserActions.registerUser(user);
    }
  },
  successContinue: function(e) {
    NavigationActions.goToHome();
    e.preventDefault();
  },
  prettyPrintError: function(err) {
    var errorInfo = [];
    for(var key in err) {
        if (err.hasOwnProperty(key)) {
            errorInfo.push(<li>{err[key]}</li>);
        }
    }
    return (<ul>
            {errorInfo}
            </ul>)
  },
  renderRegistrationState: function() {
    var rs = this.state.registration;
    if (!rs.performed) {

    return (<div></div>)
    } else  if(rs.performed && !rs.success){
        return (<div>
                Desila se pogreška pri registraciji. Detalji greške su:
                {this.prettyPrintError(rs.error)}
                </div>)
    } else if (rs.performed && rs.success) {
        return (<div>
               Uspješno ste se registrovali na Ribicu. Kliknite <a onClick={this.successContinue}>ovdje</a> za nastavak.
                </div>)
    }
  },
  render : function() {
  var cx = React.addons.classSet;
  var regSuccess = this.state.registration.performed && this.state.registration.success;
  var classes = cx({
    'hide': regSuccess
  });
  if (!this.state.registration.performed && this.state.loginState.loggedIn) {
      return (<div>Vi ste već registrovani. Uživajte u kupovini.</div>)
  }

  return (<div>
    {this.renderRegistrationState()}
    <div className={classes}>
    <div className="col-lg-6 col-md-6 col-sm-8 col-xs-12 col-centered" style={{height: 500}}>
        <div className="reglogo">
          <h1 style={{paddingTop: 40}} className="text-center">Registracija</h1>
          <br />
          <form className>
            <div className="form-group col-lg-6 col-md-6  ">
              <input style={{marginBottom: 8}} type="text" onKeyPress={this.onKeyPress} onChange={this.handleChange('firstName')} className="form-control" placeholder="Ime" />
              {this.getValidationMessages('firstName').map(this.renderErrorMessage)}

            </div>
            <div className="form-group  col-lg-6 col-md-6 ">
              <input style={{marginBottom: 8}} type="text" onKeyPress={this.onKeyPress} onChange={this.handleChange('lastName')} className="form-control" placeholder="Prezime" />
              {this.getValidationMessages('lastName').map(this.renderErrorMessage)}

            </div>
            <div className="form-group col-lg-12 col-md-12">
              <input style={{marginBottom: 8}} type="text" onKeyPress={this.onKeyPress} onChange={this.handleChange('email')} className="form-control" placeholder="Email adresa" />
              {this.getValidationMessages('email').map(this.renderErrorMessage)}

            </div>
            <div className="form-group col-lg-12 col-md-12">
              <input style={{marginBottom: 8}} type="password" onKeyPress={this.onKeyPress} onChange={this.handleChange('password')} className="form-control" placeholder="Šifra" />
              {this.getValidationMessages('password').map(this.renderErrorMessage)}

            </div>
            <div className="form-group col-lg-12 col-md-12">
              <input style={{marginBottom: 8}} type="password" onKeyPress={this.onKeyPress} onChange={this.handleChange('passwordConfirmation')} className="form-control" placeholder="Potvrda šifre" />
              {this.getValidationMessages('passwordConfirmation').map(this.renderErrorMessage)}

            </div>
            <div className="form-group col-lg-6 col-md-6 col-sm-6 col-xs-6">
              {this.renderGenderImage()}
            </div>
            <div className="radio col-lg-6 col-md-6 ">
              <h4>Moja beba (po izboru) </h4>
              <br />
              <label><input className name="option1" value="1" type="radio" id="opone" onChange={this.myBabyChange}  /> Na putu</label>
              <br />
              <label><input className name="option1" type="radio" id="optwo" onChange={this.myBabyChange}  /> Već rođena</label>
            </div>
            <div   id="gender" className={this.state.myBabyOnTheWay ? "radio col-lg-6 hide": "radio col-lg-6 "}>
              <br />
              <label><input className name="gender" type="radio" id="chkImg" value="boy" onChange={this.myBabyGenderChange} /> Dječak</label>
              <br />
              <label><input className name="gender" type="radio" id="chkImg2" value="girl" onChange={this.myBabyGenderChange} /> Djevojčica</label>
            </div>
            <div id="babydetails" className={this.state.myBabyDetailsVisible ? "" :"hide"}>
            <div className="radio col-lg-12 col-md-12">
              <input style={{marginBottom: 8}} type="text" className="form-control"  onChange={this.myBabyNameChange}  placeholder="Ime bebe" />
            </div>
            <div className=" text-center col-lg-12 col-md-12">
              Datum rođenja
            </div>
            <div className="form-group col-lg-12 col-md-12">
              <div className=" col-lg-3 col-md-3">
               {this.renderDaySelector()}
              </div>
              <div className="col-lg-5 col-md-5">
               {this.renderMonthSelector()}
              </div>
              <div className=" col-lg-4 col-md-4">
                  {this.renderYearSelector()}
              </div>
            </div>
            </div>
            <input style={{color: 'white', fontWeight: 'bold', height: 44}} type="submit" onClick={this.onRegisterClick} className=" mybutton center-block col-md-8 col-sm-8 col-xs-8 col-sm-push-2 col-xs-push-2 col-md-push-2" defaultValue="REGISTRUJ ME" />
          </form>
          <div className="text-center col-lg-12 col-md-12 col-sm-12 col-xs-12">
            <h4>Već imate profil? <Link to="login"><span> Prijavite se</span></Link></h4>
          </div>
        </div>
      </div>
      </div>
      </div>
);
  /*
    return (<div>
      <span className="h3">Registracija</span>
           {this.renderRegistrationState()}
      <div className="center" className={classes}>
        <form className="form-horizontal">

        <fieldset>
        <div className="form-group">
            <label for="firstName" className="col-md-4 control-label">Ime</label>
            <div className="col-md-4">
              <input type="text" onKeyPress={this.onKeyPress} onChange={this.handleChange('firstName')} className="form-control" id="firstName" placeholder="Ime"/>
              {this.getValidationMessages('firstName').map(this.renderErrorMessage)}
            </div>
        </div>

        <div className="form-group">
            <label for="lastName" className="col-md-4 control-label">Prezime</label>
            <div className="col-md-4">
              <input type="text" onKeyPress={this.onKeyPress} onChange={this.handleChange('lastName')} className="form-control" id="lastName" placeholder="Prezime"/>
              {this.getValidationMessages('lastName').map(this.renderErrorMessage)}
            </div>
        </div>
        <div className="form-group">
            <label for="email" className="col-md-4 control-label">Email</label>
            <div className="col-md-4">
              <input type="text" onKeyPress={this.onKeyPress} onChange={this.handleChange('email')} className="form-control" id="email" placeholder="Email Adresa"/>
              {this.getValidationMessages('email').map(this.renderErrorMessage)}
            </div>
        </div>
        <div className="form-group">
            <label for="password" className="col-md-4 control-label">Šifra</label>
            <div className="col-md-4">
              <input type="password" onKeyPress={this.onKeyPress} onChange={this.handleChange('password')} className="form-control" id="password" placeholder="Šifra"/>
              {this.getValidationMessages('password').map(this.renderErrorMessage)}
            </div>
        </div>
        <div className="form-group">
            <label for="password_confirmation" className="col-md-4 control-label">Potvrda šifre</label>
            <div className="col-md-4">
              <input type="password"  onKeyPress={this.onKeyPress} onChange={this.handleChange('passwordConfirmation')} className="form-control" id="password_confirmation" placeholder="Podvrda šifre"/>


              {this.getValidationMessages('passwordConfirmation').map(this.renderErrorMessage)}
            </div>
        </div>

        <div className="form-group">
            <label for="my_baby" className="col-md-4 control-label">Moja beba</label>
            <div className="col-md-4">
              <input type="radio" onChange={this.myBabyChange}  name="my_baby" id="already_born" /> Vec rođena
              <input type="radio" onChange={this.myBabyChange} value="1" id="on_the_way" name="my_baby" />Na putu
            </div>
        </div>

        {this.renderBabyDetails()}

        <div className="form-group">
            <div className="col-md-4">

            </div>
            <div className="col-md-4">
            <button onClick={this.onRegisterClick} type="button" className="btn btn-success btn-lg">
            Registruj me
            </button>
            </div>
        </div>
        </fieldset>
        </form>
      </div>
      </div>); */
  }
})
module.exports = Register;
