import PropTypes from 'prop-types';
import React from 'react';
import classnames from 'classnames';
import FieldError from './FieldError';

export default function FieldGroup (props) {
    const { containerClassName, labelText, helpText, error, required } = props;
    const hasError = Array.isArray(error) ? error.length > 0 : !!error;

    return (
        <div className={classnames('cheryl__field-group', containerClassName, { cheryl__error: hasError })}>
            <label>
                {labelText && <span className="cheryl__label">{labelText}</span>}
                {required && <span className="cheryl__required" />}
                {props.children}
                {!hasError && helpText && (<div className="cheryl__help-text">{helpText}</div>)}
                {hasError && <FieldError error={error} />}
            </label>
        </div>
    );
}

FieldGroup.propTypes = {
    containerClassName: PropTypes.string,
    labelText: PropTypes.string,
    helpText: PropTypes.string,
    error: PropTypes.oneOfType([PropTypes.string, PropTypes.array]),
    children: PropTypes.element,
    required: PropTypes.bool,
};
