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

import './styles/Textarea.scss';
import { generateUniqueID } from '../../tools/helpers';

const n = createNamespace('Textarea');

const Textarea = ({
    name,
    label,
    defaultValue,
    error,
    inputRef,
    hiddenLabel,
    placeholder,
    required,
    ...otherProps
}) => {
    if (!label) {
        return null;
    }

    const controlModifier = error && 'with-errors';
    const labelTextModifier = hiddenLabel ? 'hidden' : null;
    const errorId = generateUniqueID(['error', name]);

    return (
        <div {...n('group').props}>
            <FormLabel
                labelText={label}
                required={required}
                labelProps={n('label').withTestId().props}
                textProps={n('text', labelTextModifier).props}
                htmlFor={name}
            >
                <textarea
                    id={name}
                    name={name}
                    ref={inputRef}
                    defaultValue={defaultValue}
                    placeholder={placeholder}
                    aria-invalid={Boolean(error)}
                    aria-describedby={Boolean(error) && errorId}
                    {...otherProps}
                    {...n('control', controlModifier).props}
                />
            </FormLabel>
            {error && (
                <span {...n('error').withTestId().props} aria-live="polite" id={errorId}>
                    {error}
                </span>
            )}
        </div>
    );
};

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

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

export default Textarea;
