import React, {Component} from 'react';
import PropTypes from 'prop-types';
import Label from '../Label';
import Hint from '../Hint';
import Tooltip from '../Tooltip';
import classNames from 'classnames';
import THEME from '../RadioGroup/theme';
import './styles.scss';

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

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

    handleInputChange(event) {
        const value = event.target.value;
        this.props.onChange(value);
    }

    renderTooltip() {
        return (
            <Tooltip
                id={`${this.props.id}-tooltip`}
                tip={this.props.tooltip}
                place="top"
            >
                {this.renderLabel()}
            </Tooltip>
        );
    }

    renderLabel() {
        return (
            <Label
                label={this.props.label}
                for={this.props.id}
                className="RadioButton__label"
            />
        );
    }

    render() {
        const hint = this.props.hint && <Hint message={this.props.hint} />;
        const tooltip = this.props.tooltip && this.renderTooltip();
        const classes = classNames('RadioOption', `RadioOption_${this.props.theme}`, {
            RadioOption_active: this.props.isChecked,
        });

        return (
            <div className={classes}>
                <div>
                    <input
                        className="RadioButton"
                        type="radio"
                        onChange={this.handleInputChange}
                        checked={this.props.isChecked}
                        disabled={this.props.isDisabled}
                        id={this.props.id}
                        value={this.props.value}
                    />
                    {!tooltip && this.renderLabel()}
                    {tooltip}
                </div>
                {hint}
            </div>
        );
    }
}

RadioOption.propTypes = {
    isDisabled: PropTypes.bool,
    isChecked: PropTypes.bool,
    onChange: PropTypes.func,
    label: PropTypes.string.isRequired,
    value: PropTypes.string.isRequired,
    id: PropTypes.string.isRequired,
    hint: PropTypes.string,
    tooltip: PropTypes.string,
    theme: PropTypes.oneOf([THEME.RADIO, THEME.RADIO_HORIZONTAL, THEME.TAB]),
};

RadioOption.defaultProps = {
    isDisabled: false,
    isChecked: false,
    onChange: () => {},
    hint: null,
    tooltip: '',
    theme: THEME.RADIO,
};

export default RadioOption;
