import PropTypes from 'prop-types';

function isInvalid(props) {
    if (!props || !props.errors) {
        return false;
    }
    if (props.errors instanceof Array) {
        return props.errors.length > 1 || Boolean(props.errors[0]);
    }

    return Boolean(props.errors);
}

const Item = props => {
    const className = [
        Item._name,
        props.required ? `${Item._name}_required` : null,
        isInvalid(props) ? `${Item._name}_invalid` : null,
        props.className,
    ].filter(Boolean).join(' ');

    return (
        <div className={className}>
            {props.children}
            <Item.Error message={props.errors} />
        </div>
    );
};

Item._name = 'lego-form-item';

// @if NODE_ENV='development'
Item.propTypes = {
    errors: PropTypes.any,
    required: PropTypes.bool,
};
// @endif

Item.Error = props => {
    const { message } = props;
    let content;

    if (message instanceof Array) {
        if (message.length > 1) {
            content = <ul>{message.map((error, index) => <li key={index}>{error}</li>)}</ul>;
        } else if (message.length === 1) {
            content = message[0];
        }
    } else if (message) {
        content = message;
    }

    if (!content) {
        return null;
    }

    return <div className={Item.Error._name}>{content}</div>;
};

Item.Error._name = 'lego-form-item-error';

export default Item;
