import _toConsumableArray from 'babel-runtime/helpers/toConsumableArray';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _createClass from 'babel-runtime/helpers/createClass';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import React from 'react';
import CheckItem from './index';
// eslint-disable-next-line react/prefer-stateless-function

var OptionalLabel = function (_React$Component) {
    _inherits(OptionalLabel, _React$Component);

    function OptionalLabel(props) {
        _classCallCheck(this, OptionalLabel);

        var _this = _possibleConstructorReturn(this, (OptionalLabel.__proto__ || Object.getPrototypeOf(OptionalLabel)).call(this, props));

        _this.handleChange = function (e, v) {
            var onChange = _this.props.onChange;

            var value = [].concat(_toConsumableArray(_this.state.value));
            var checked = e.target.checked;

            if (checked) {
                value.push(v.value);
            } else {
                value.splice(value.indexOf(v.value), 1);
            }
            _this.setState({ value: value });
            if (onChange) {
                onChange(value);
            }
        };
        _this.state = {
            value: props.value || props.defaultValue
        };
        return _this;
    }

    _createClass(OptionalLabel, [{
        key: 'render',
        value: function render() {
            var _this2 = this;

            var options = this.props.options;
            var value = this.state.value;

            return React.createElement(
                'div',
                null,
                options.map(function (v) {
                    return React.createElement(CheckItem, { key: v.value, label: v.label, checked: Array.isArray(value) && value.length > 0 ? value.includes(v.value) : false, onChange: function onChange(e) {
                            return _this2.handleChange(e, v);
                        } });
                })
            );
        }
    }], [{
        key: 'getDerivedStateFromProps',
        value: function getDerivedStateFromProps(nextProps) {
            if ('value' in nextProps) {
                return {
                    value: nextProps.value || []
                };
            }
            return null;
        }
    }]);

    return OptionalLabel;
}(React.Component);

export default OptionalLabel;