import React from 'react';
import { Model } from 'front';
import './radio.less';

/**\

    title: RadioOption
    category: model
    description:
        A base interface for what is required in a radio option.

\**/
class RadioOption extends Model {
    constructor(data) {
        super({
            title: '',
            value: null
        });

        this.fill(data);
    }
}

/**\

    title: Radio
    category: component
    description:
        A radio select-one component
    props:
        className[String]:
            arbitrary class names to append to the radio component.
        onSelect[Function]:
            a callback for when an option is selected. The value of the
            selected option is passed as the first argument.
        items[Array]:
            An array of models for the available options. Use RadioOption or
            a raw javascript object with the same properties title & value.
        value:
            A value that should match the value of one of the options.

\**/
class Radio extends React.Component {
    static defaultProps = {
        items: []
    }

    state = {
        at: -1
    }

    constructor(props) {
        super(props);

        this.state.at = props.items.findIndex((item) =>
            props.value === item.value
        );
    }

    componentWillReceiveProps(nextProps) {
        const nextState = {};

        nextState.at = nextProps.items.findIndex((item) =>
            nextProps.value === item.value
        );

        this.setState(nextState);
    }

    onSelect(idx) {
        /* istanbul ignore if: hard to test edge case */
        if (idx < 0 || idx >= this.props.items.length) {
            return;
        }

        this.setState({ at: idx });
        if (typeof this.props.onSelect === 'function') {
            this.props.onSelect(this.props.items[idx].value);
        }
    }

    renderOptions() {
        return this.props.items.map((item, idx) => {
            let classer = 'option';

            if (this.state.at === idx) {
                classer += ' selected';
            }

            return (
                <div className={ classer }
                    key={ item.value }
                    onClick={ () => this.onSelect(idx) }>
                    { item.title }
                </div>
            );
        });
    }

    render() {
        let classer = 'radio';

        if (this.props.className) {
            classer += ` ${this.props.className}`;
        }

        return (
            <div className={ classer }>
                { this.renderOptions() }
            </div>
        );
    }
}

export default Radio;
export { RadioOption };
