import React from 'react';
import PropTypes from 'prop-types';
import { createNamespace } from '../../tools/namingTools';
// IMPORTANT: (s)css should be imported after other atoms/components
import './styles/CheckboxUncontrolled.scss';

const n = createNamespace('CheckboxUncontrolled');

const CheckboxUncontrolled = ({
    title,
    label,
    name,
    value,
    required,
    inputRef,
    error
}) => {
    const inputId = `${name}:${value}`;
    const textModifiers = [
        error && 'error'
    ];
    const renderInput = () => (
        <div {...n('group').props}>
            <input
                {...n('control').withE2EId().withTestId().props}
                type="checkbox"
                name={name}
                id={inputId}
                aria-label={label}
                required={required}
                value={value}
                ref={inputRef}
            />
            <label {...n('text', textModifiers).props} htmlFor={inputId}>{label}</label>
            {error && (
                <span {...n('error').props} aria-live="assertive">
                    {error}
                </span>
            )}
        </div>
    );

    return (
        <div {...n('container').props}>
            {title ? (
                <fieldset {...n('fieldset').props}>
                    <legend {...n('legend').props}>{title}</legend>
                    {renderInput()}
                </fieldset>
            ) : renderInput()}
        </div>
    );
};

CheckboxUncontrolled.propTypes = {
    name: PropTypes.string.isRequired,
    title: PropTypes.string,
    value: PropTypes.string,
    label: PropTypes.oneOfType([PropTypes.string, PropTypes.element]),
    required: PropTypes.bool,
    inputRef: PropTypes.func,
    error: PropTypes.string
};

CheckboxUncontrolled.defaultProps = {
    title: null,
    value: null,
    label: 'Checkbox',
    required: false,
    inputRef: () => null,
    error: null
};

export default CheckboxUncontrolled;
