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

import {filterKeyCodes} from '../../utils/functions';

import {CatalogItemIcon} from './CatalogItemIcon';
import {CatalogSimplePrice} from './CatalogSimplePrice';

export class CatalogGridItem extends React.PureComponent<any> {
    static propTypes = {
        testAutomationId: PropTypes.string,
        name: PropTypes.string.isRequired,
        description: PropTypes.string,
        icon: PropTypes.string,
        color: PropTypes.string,
        onClick: PropTypes.func,
        price: PropTypes.shape({
            pricePurchase: PropTypes.object,
            priceAnnual: PropTypes.object,
            priceMonthly: PropTypes.object,
            isPriceFrom: PropTypes.bool
        })
    };

    static defaultProps = {
        testAutomationId: 'catalogGridItem',
        description: null,
        icon: null,
        color: null,
        price: null,
        onClick: () => {}
    };

    handleKeyDown = filterKeyCodes(this.props.onClick);

    renderDescription() {
        const {description, price} = this.props;

        if (!description && !price) {
            return null;
        }

        if (price) {
            const {pricePurchase, priceAnnual, priceMonthly, isPriceFrom} = price;

            return (
                <CatalogSimplePrice
                    isCentered
                    pricePurchase={pricePurchase}
                    priceAnnual={priceAnnual}
                    priceMonthly={priceMonthly}
                    isPriceFrom={isPriceFrom}
                />
            );
        }

        return (
            <div className="rc-catalog-grid-item__desc" data-test-automation-id="description">
                {description}
            </div>
        );
    }

    renderIcon() {
        const {icon, color} = this.props;

        if (React.isValidElement(icon)) {
            return icon;
        }

        return <CatalogItemIcon isRound size={90} iconName={icon} backgroundColor={color} />;
    }

    render() {
        const {testAutomationId, name, onClick} = this.props;

        return (
            <div
                data-test-automation-id={testAutomationId}
                className="rc-catalog-grid-item__block"
                role="button"
                onClick={onClick}
                onKeyDown={this.handleKeyDown}
                tabIndex={0}>
                {this.renderIcon()}
                <div className="rc-catalog-grid-item__name" data-test-automation-id="name">
                    {name}
                </div>
                {this.renderDescription()}
            </div>
        );
    }
}
