import React from 'react';
import PropTypes from 'prop-types';
import { createNamespace } from '../../tools/namingTools';

import './styles/Textarea.scss';

const n = createNamespace('Textarea');

const Textarea = ({
    name,
    label,
    defaultValue,
    error,
    inputRef,
    hiddenLabel,
    placeholder,
    ...otherProps
}) => {
    const controlModifier = error && 'with-errors';
    const labelTextModifier = hiddenLabel ? 'hidden' : null;

    return (
        <div {...n('group').props}>
            <label {...n('label').props} htmlFor={name}>
                <span {...n('text', labelTextModifier).props}>{label}</span>
                <textarea
                    id={name}
                    name={name}
                    ref={inputRef}
                    defaultValue={defaultValue}
                    placeholder={placeholder}
                    {...otherProps}
                    {...n('control', controlModifier).props}
                />
            </label>
            {error && (
                <span {...n('error').props} aria-live="assertive">
                    {error}
                </span>
            )}
        </div>
    );
};

Textarea.propTypes = {
    name: PropTypes.string.isRequired,
    label: PropTypes.string,
    defaultValue: PropTypes.string,
    error: PropTypes.string,
    placeholder: PropTypes.string,
    inputRef: PropTypes.func,
    hiddenLabel: PropTypes.bool
};

Textarea.defaultProps = {
    label: '',
    defaultValue: '',
    error: null,
    inputRef: null,
    placeholder: null,
    hiddenLabel: false
};

export default Textarea;
