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

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

import {CatalogPrice} from './CatalogPrice';

export class CatalogGridItem extends React.PureComponent<any> {
    static propTypes = {
        testAutomationId: PropTypes.string,
        category: PropTypes.bool,
        name: PropTypes.string.isRequired,
        description: PropTypes.string,
        icon: PropTypes.node.isRequired,
        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',
        category: false,
        description: 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 (
                <Card.Content center>
                    <CatalogPrice
                        isCentered
                        pricePurchase={pricePurchase}
                        priceAnnual={priceAnnual}
                        priceMonthly={priceMonthly}
                        isPriceFrom={isPriceFrom}
                    />
                </Card.Content>
            );
        }

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

    renderIcon() {
        return (
            <Card.Content center addTopOffset addBottomOffset>
                {React.cloneElement(this.props.icon, {size: 90, isRound: true})}
            </Card.Content>
        );
    }

    renderName() {
        const {name} = this.props;

        return (
            <Card.Content center>
                <div className="rc-catalog-grid-item__name" data-test-automation-id="name">
                    {name}
                </div>
            </Card.Content>
        );
    }

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

        return (
            <Card secondary={category} testAutomationId={testAutomationId} onClick={onClick}>
                {this.renderIcon()}
                {this.renderName()}
                {this.renderDescription()}
            </Card>
        );
    }
}
