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

const n = createNamespace('Checkbox');

const Checkbox = ({
    title,
    label,
    ariaLabel,
    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}>
                    <input
                        {...n('control', size).withE2EId().withTestId().props}
                        type="checkbox"
                        aria-label={ariaLabel}
                        name={name}
                        id={name}
                        required={required}
                        value={finalIsChecked}
                        onChange={finalOnChange}
                        ref={inputRef}
                    />
                    <span {...n('text', textModifiers).props} aria-hidden={Boolean(ariaLabel)}>{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]),
    ariaLabel: PropTypes.string,
    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',
    ariaLabel: null,
    size: null,
    required: false,
    isChecked: null,
    onChange: null,
    inputRef: () => null,
    error: null
};

export default Checkbox;
