import React, {Component} from 'react';
import PropTypes from 'prop-types';
import RadioOption from '../RadioOption';
import Error from '../ErrorLabel';
import classNames from 'classnames';
import THEME from './theme';
import './styles.scss';

class RadioGroup extends Component {
    constructor(props) {
        super(props);

        this.state = {
            activeState: this.props.activeState,
            errors: this.props.errors,
        };

        this.handleInputChange = this.handleInputChange.bind(this);
    }

    componentWillReceiveProps(nextProps) {
        this.setState({errors: nextProps.errors.length ? nextProps.errors : []});

        const newOptionValues = (nextProps.options || []).map(option => option.value);
        const newActiveState = nextProps.activeState || newOptionValues[0];
        if (newActiveState) {
            this.setState({
                activeState: newOptionValues.includes(this.state.activeState) ? this.state.activeState : newActiveState,
            });
        }
    }

    handleInputChange(value) {
        const errors = value ? [] : this.state.errors;

        this.setState({
            errors,
            activeState: value,
        }, () => {
            this.props.onChange(value);
        });
    }

    render() {
        const classes = classNames('RadioGroup', `RadioGroup_${this.props.theme}`);
        const errors = this.state.errors.length ? (
            <div className="RadioGroup__errors">
                <Error errors={this.state.errors}/>
            </div>
        ) : null;
        const buttons = this.props.options.map((option) => {
            return (
                <RadioOption
                    id={option.id}
                    key={option.id}
                    label={option.label}
                    value={option.value}
                    onChange={this.handleInputChange}
                    isChecked={option.value === this.state.activeState}
                    isDisabled={this.props.isDisabled || option.isDisabled}
                    hint={option.hint}
                    tooltip={option.tooltip}
                    theme={this.props.theme}
                />
            );
        });

        return (
            <div className={classes}>
                <div className="RadioGroup__options">
                    {buttons}
                </div>
                {errors}
            </div>
        );
    }
}

RadioGroup.propTypes = {
    options: PropTypes.array.isRequired,
    activeState: PropTypes.string,
    isDisabled: PropTypes.bool,
    onChange: PropTypes.func,
    errors: PropTypes.array,
    theme: PropTypes.string,
};

RadioGroup.defaultProps = {
    activeState: '',
    isDisabled: false,
    onChange: () => {},
    errors: [],
    theme: THEME.RADIO,
};

export default RadioGroup;
