import React from 'react';
import PropTypes from 'prop-types';
import { createNamespace } from '../../tools/namingTools';
import { useControlledInput } from '../../tools/useControlledInput';
import { SMALL } from '../../constants/sizes';
import './styles/Checkbox.scss';

const n = createNamespace('Checkbox');
const Checkbox = ({
    title,
    label,
    name,
    size,
    required,
    isChecked,
    onChange,
    inputRef,
    error
}) => {
    // if input is uncontrolled, make sure it becomes controlled, because we need its value to display it correctly
    const [finalIsChecked, finalOnChange] = useControlledInput(isChecked, onChange, e => e.currentTarget.checked);
    const renderInput = () => {
        const textModifiers = [
            size,
            error && 'error',
            finalIsChecked && 'checked'
        ];
        return (
            <div {...n('group').props}>
                <label {...n('label').withE2EId().props} htmlFor={name}>
                    <input
                        {...n('control', size).withE2EId().props}
                        type="checkbox"
                        name={name}
                        id={name}
                        aria-label={label}
                        required={required}
                        value={finalIsChecked}
                        onChange={finalOnChange}
                        ref={inputRef}
                    />
                    <span {...n('text', textModifiers).props}>{label}</span>
                </label>
                {error && (
                    <span {...n('error').props} aria-live="assertive">
                        {error}
                    </span>
                )}
            </div>
        );
    };

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

Checkbox.propTypes = {
    title: PropTypes.string,
    name: PropTypes.string.isRequired,
    size: PropTypes.oneOf([SMALL.value]),
    label: PropTypes.oneOfType([PropTypes.string, PropTypes.element]),
    required: PropTypes.bool,
    isChecked: PropTypes.bool,
    onChange: PropTypes.func,
    inputRef: PropTypes.func,
    error: PropTypes.string
};

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

export default Checkbox;
