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

const n = createNamespace('ToggleSwitch');
const ToggleSwitch = ({
    name,
    size,
    legend,
    showLegend,
    options,
    onChange
}) => {
    if (!options || !options.length) {
        return null;
    }

    const radioGroupId = `radioGroup-${name}`;

    const renderRadioInput = item => (
        <label htmlFor={item.id} key={item.id} {...n('label').withE2EId().props}>
            <input
                type="radio"
                name={name}
                id={item.id}
                value={item.value}
                checked={item.selected || false}
                onChange={onChange}
                {...n('input').props}
            />
            <span {...n('text').props}>
                {item.iconType ? (
                    <>
                        <Icon type={item.iconType} />
                        <span className="sr-only">{item.label}</span>
                    </>
                ) : (
                    item.label
                )}
            </span>
        </label>
    );

    return options && options.length ? (
        <div {...n('group', size).props} role="radiogroup" aria-labelledby={radioGroupId}>
            <span id={radioGroupId} {...n('legend', showLegend ? '' : 'hidden').props}>{legend}</span>
            {options.map(renderRadioInput)}
        </div>
    ) : '';
};

ToggleSwitch.propTypes = {
    name: PropTypes.string.isRequired,
    size: PropTypes.oneOf(['small']),
    legend: PropTypes.string,
    showLegend: PropTypes.bool,
    options: PropTypes.arrayOf(PropTypes.shape({
        label: PropTypes.string,
        id: PropTypes.string,
        value: PropTypes.string,
        iconType: PropTypes.string,
        selected: PropTypes.bool
    })),
    onChange: PropTypes.func
};

ToggleSwitch.defaultProps = {
    options: [],
    size: null,
    legend: '',
    showLegend: false,
    onChange: () => {}
};

export default ToggleSwitch;
