import PropTypes from 'prop-types';
import React, { Component } from 'react';
import classnames from 'classnames';
import injectSheet from 'react-jss';
import intersection from 'lodash/intersection';
import includes from 'lodash/includes';

import styles from './styles/ButtonSelect';

export class Button extends Component {
    constructor(){
        super();
        this.onClick = this.onClick.bind(this);
    }
    
    onClick(){
        const { onChange } = this.props;
        onChange(this.props.value);
    }
    
    render(){
        const { isSelected, label, classes } = this.props;
        const className = classnames(classes.button, { [classes.buttonActive]: isSelected });
        return (
            <button className={className} onClick={this.onClick}>{ label }</button>
        );
    }
}

Button.propTypes = {
    isSelected: PropTypes.bool,
    value: PropTypes.any,
    label: PropTypes.string,
    onChange: PropTypes.func,
    classes: PropTypes.object
};

export class ButtonSelect extends Component {
    constructor(){
        super();
        this.onButtonClick = this.onButtonClick.bind(this);
    }
    
    onButtonClick(buttonValue){
        const { value, onChange, exclusiveOptions } = this.props;
        let newValue;
        
        if (includes(value, buttonValue)) {
            newValue = value.filter(item => buttonValue !== item);
        } else {
            const exclusiveValueAlreadySelected = !!intersection(exclusiveOptions, value).length;
            const newValueIsExclusive = includes(exclusiveOptions, buttonValue);
            
            if (exclusiveValueAlreadySelected || newValueIsExclusive) {
                newValue = [buttonValue];
            } else {
                newValue = value.concat([buttonValue]);
            }
            
            
        }
        
        onChange(newValue);
    }
    
    render(){
        const { options, value, classes } = this.props;

        return (
            <div className={classes.buttonSelect}>
                {
                    options.map(option => (
                        <Button
                            classes={classes}
                            value={option.value}
                            key={option.value}
                            label={option.label}
                            onChange={this.onButtonClick}
                            isSelected={value.indexOf(option.value) > -1}
                        />
                    ))
                }
            </div>
        );
    }
}

ButtonSelect.propTypes = {
    exclusiveOptions: PropTypes.array,
    options: PropTypes.array,
    value: PropTypes.array,
    onChange: PropTypes.func,
    classes: PropTypes.object
};

ButtonSelect.defaultProps = {
    exclusiveOptions: []
};

export default injectSheet(styles)(ButtonSelect);
