import React from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';

import {Icon} from '../Icon';

const COLORS = ['#ff4c57', '#00bcff', '#8b7cff', '#19adcf', '#ff7c00'];

const getColorForString = text => {
    const numberHash = text.split('').reduce((acc, char) => char.charCodeAt(0), 0);

    return COLORS[numberHash % COLORS.length];
};

export class CatalogItemIcon extends React.PureComponent {
    static propTypes = {
        iconName: PropTypes.string,
        backgroundColor: PropTypes.string,
        size: PropTypes.number,
        isRound: PropTypes.bool,
        testAutomationId: PropTypes.string
    };

    static defaultProps = {
        iconName: null,
        backgroundColor: null,
        size: 60,
        isRound: null,
        testAutomationId: 'catalogItemIcon'
    };

    renderIcon() {
        const {iconName} = this.props;

        if (!iconName) {
            return (
                <div className="rc-catalog-item-icon__icon--close">
                    <Icon name="close" />
                </div>
            );
        }

        return (
            <div className="rc-catalog-item-icon__icon">
                <Icon name={iconName} />
            </div>
        );
    }

    render() {
        const {testAutomationId, iconName, backgroundColor, size, isRound} = this.props;

        const className = classnames('rc-catalog-item-icon', {
            'rc-catalog-item-icon--round': isRound,
            'rc-catalog-item-icon--placeholder': !iconName
        });

        const style = {
            fontSize: `${size}px`
        };

        if (iconName) {
            style.backgroundColor = backgroundColor || getColorForString(iconName);
        }

        return (
            <div style={style} className={className} data-test-automation-id={testAutomationId}>
                {this.renderIcon()}
            </div>
        );
    }
}
