import React, {Component} from 'react';
import PropTypes from 'prop-types';
import './styles.scss';

function ListItem(props) {
    return (
        <li className="Error__input-error">
            {props.value}
        </li>
    );
}

ListItem.propTypes = {
    value: PropTypes.string.isRequired,
};

function ErrorsList(props) {
    const listClassName = props.errors.length === 1
        ? 'Error__bubble_single'
        : '';

    const listItems = props.errors.map((error, index) => {
        return (<ListItem
            value={error}
            key={String(index)}
        />);
    });

    function toggleBubbleClassName(className) {
        return `${className}${props.isActive ? ' Error__bubble' : ''}`;
    }

    return (
        <ul className={toggleBubbleClassName(listClassName)}>
            {listItems}
        </ul>
    );
}

ErrorsList.propTypes = {
    errors: PropTypes.array.isRequired,
    isActive: PropTypes.bool.isRequired,
};

class Error extends Component {
    constructor(props) {
        super(props);

        this.state = {
            isActive: false,
        };

        this.handleClick = this.handleClick.bind(this);
    }

    handleClick() {
        this.setState({
            isActive: !this.state.isActive,
        });
    }

    render() {
        if (!this.props.errors.length) {
            return null;
        }

        const errorsList = this.state.isActive && (
            <ErrorsList
                errors={this.props.errors}
                isActive={this.state.isActive}
            />
        );

        return (
            <div
                className="Error"
                role="presentation"
                onClick={this.handleClick}
            >
                {errorsList}
            </div>
        );
    }
}

Error.propTypes = {
    errors: PropTypes.array.isRequired,
};

export default Error;
