import React from 'react';
import PropTypes from 'prop-types';
import './styles/RadioGroup.scss';
import { createNamespace } from '../../tools/namingTools';

const nameSpace = 'RadioGroup';
const n = createNamespace(nameSpace);

const RadioGroup = ({
    name,
    options,
    value,
    onChange
}) => (
    <React.Fragment>
        {options.map(option => {
            const isChecked = (value === option.value) || false;
            const inputId = `${name}_${option.value}`;
            return (
                <div {...n('form-group').props} key={option.value}>
                    <label {...n('label').props} htmlFor={inputId}>
                        <input
                            {...n('control').props}
                            type="radio"
                            name={name}
                            id={inputId}
                            value={option.value}
                            checked={isChecked}
                            onChange={onChange}
                        />
                        <span {...n('text').props}>{option.label}</span>
                    </label>
                </div>
            );
        })}
    </React.Fragment>
);

const optionPropTypes = PropTypes.shape({
    label: PropTypes.string,
    value: PropTypes.string
});

RadioGroup.propTypes = {
    options: PropTypes.arrayOf(optionPropTypes),
    value: PropTypes.string,
    name: PropTypes.string.isRequired,
    onChange: PropTypes.func
};

RadioGroup.defaultProps = {
    options: [],
    value: null,
    onChange: null
};

export default RadioGroup;
