var React = require('react/addons');
var TextControl = require('../../../../components/form/TextControl');
var Actions = require('../../actions/AdminGroup');


var Component = React.createClass({
  mixins: [React.addons.LinkedStateMixin],
  getInitialState: function () {

    return {};
  },
  componentWillReceiveProps: function (nextProps) {

    if (!this.state.hydrated) {
      this.setState({
        hydrated: nextProps.data.hydrated,
        name: nextProps.data.name
      });
    }
  },
  handleSubmit: function (event) {

    event.preventDefault();
    event.stopPropagation();

    Actions.saveDetails({
      id: this.props.data._id,
      name: this.state.name
    });
  },
  render: function () {

    var alerts = [];
    if (this.props.data.success) {
      alerts.push(<div key="success" className="alert alert-success">
        Success. Changes have been saved.
      </div>);
    }
    else if (this.props.data.error) {
      alerts.push(<div key="danger" className="alert alert-danger">
        {this.props.data.error}
      </div>);
    }

    var notice;
    if (!this.props.data.hydrated) {
      notice = <div className="alert alert-info">
        Loading data...
      </div>;
    }

    var formElements;
    if (this.props.data.hydrated) {
      formElements = <fieldset>
        <legend>Details</legend>
        {alerts}
        <TextControl
          name="name"
          label="Name"
          hasError={this.props.data.hasError.name}
          valueLink={this.linkState('name')}
          help={this.props.data.help.name}
          disabled={this.props.data.loading}
        />
      </fieldset>;
    }

    return (
      <form onSubmit={this.handleSubmit}>
        {notice}
        {formElements}
      </form>
    );
  }
});


module.exports = Component;
