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

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

const RadioGroup = ({
    label,
    name,
    options,
    value,
    onChange
}) => {
    const radioGroupId = `radioGroup-${name}`;

    return (
        <div {...n('radio-group').props} role="radiogroup" aria-labelledby={radioGroupId}>
            <span {...n('legend', 'hidden').props} id={radioGroupId}>{label}</span>
            {options.map(({ value: optionValue, label: optionLabel }) => {
                const isChecked = (value === optionValue) || false;
                const inputId = `${name}_${optionValue || optionLabel}`.toLowerCase();

                return (
                    <div {...n('form-group').props} key={generateUniqueID([optionValue, optionLabel])}>
                        <label {...n('label').props} htmlFor={inputId}>
                            <input
                                {...n('control').props}
                                type="radio"
                                name={name}
                                id={inputId}
                                value={optionValue}
                                checked={isChecked}
                                onChange={onChange}
                            />
                            <span {...n('text').props}>{optionLabel}</span>
                        </label>
                    </div>
                );
            })}
        </div>
    );
};

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

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

RadioGroup.defaultProps = {
    options: [],
    label: 'Radio group',
    value: null,
    onChange: null
};

export default RadioGroup;
