import React, { Component, PropTypes } from 'react';
import cn from 'classnames';
import UI from 'jqestate.ru/components/ui';
import 'jqestate.ru/styles/ui/checkbox';

class CheckboxGroup extends Component {
  static propTypes = {
    reference: PropTypes.string.isRequired,
    children: PropTypes.node.isRequired,
    handleChange: PropTypes.func.isRequired,
    selected: PropTypes.array,
  }

  constructor(props) {
    super(props);

    this.state = {
      items: props.items,
    };
  }

  componentWillReceiveProps(nextProps) {
    const arrToSet = [];
    const { items = [] } = nextProps;
    const selected = (nextProps.selected && nextProps.selected.slice()) || [];

    items.forEach(item => {
      const exist = selected.some((selectedItem, index) => {
        if (item.value === selectedItem) return selected.splice(index, 1);
      });

      arrToSet.push({
        ...item,
        checked: !!exist,
      });
    });


    this.setState({
      items: arrToSet,
    });
  }

  handleChange(key, val) {
    const ref = this.props.reference;
    const { selected = [] } = this.props;

    if (val) {
      selected.push(key);
    } else {
      const indexed = selected.indexOf(key);
      if (indexed !== -1) {
        selected.splice(indexed, 1);
      }
    }

    this.props.handleChange(ref, selected);
  }

  render() {
    return (
      <div className={cn(`form-group`, this.props.className)}>
        <label className="label-heading">
          {this.props.children}
        </label>

        {this.state.items.map(item =>
          <div className="checkbox-container" key={item.value}>
            <UI.Checkbox handleChange={::this.handleChange} reference={item.value} checked={item.checked}>
              {item.label}
            </UI.Checkbox>
          </div>
        )}
      </div>
    );
  }
}

export default CheckboxGroup;
