import React from 'react';
import './index.styl';

const RadioGroup = React.createClass({

    _name: 'lego-radio-group',

    getInitialState(props) {
        if (!props) {
            props = this.props;
        }

        return {
            val: props.val,
            disabled: props.disabled,
            busy: props.busy,
            opaque: props.opaque,
        };
    },

    componentWillReceiveProps(nextProps) {
        this.setState(this.getInitialState(nextProps));
    },

    _renderItem(item, index) {
        const base = `${this._name}-item`;
        const className = [
            base,
            this.state.val === item.val ? `${base}_selected` : null,
            typeof item.content === 'string' ? `${base}_plain` : null,
            this.state.busy ? `${base}_busy` : null,
        ].filter(Boolean).join(' ');

        return (
            <label className={className} key={index}>
                <input
                    type="radio"
                    className={`${this._name}__control`}
                    name={this.props.name}
                    value={item.val}
                    checked={this.state.val === item.val}
                    disabled={this.state.disabled}
                    onChange={this._handleChange}
                />
                <div className={`${this._name}__content`}>
                    {item.content}
                </div>
            </label>
        );
    },

    _handleChange(event) {
        const val = event.target.value;

        if (val === this.state.val) {
            return;
        }

        this.setState({ val });

        setTimeout(() => {
            if (this.props.onChange) {
                this.props.onChange(val);
            }
        }, 0);
    },

    render() {
        const className = [
            this._name,
            this.state.opaque ? `${this._name}_opaque` : null,
            this.state.disabled ? `${this._name}_disabled` : null,
        ].filter(Boolean).join(' ');

        return (
            <div className={className}>
                {this.props.options.map(this._renderItem)}
            </div>
        );
    },

});

export default RadioGroup;
