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

import {InfoCard} from '../InfoCard';
import {FlexBlock} from '../flexBlock/FlexBlock';
import {scrollElementIntoView} from '../../utils/functions';

export class CatalogGridDetails extends React.Component<any> {
    static propTypes = {
        testAutomationId: PropTypes.string,
        index: PropTypes.number.isRequired,
        colCount: PropTypes.number.isRequired,
        icon: PropTypes.node.isRequired,
        title: PropTypes.string.isRequired,
        close: PropTypes.func,
        shouldScrollIntoView: PropTypes.bool
    };

    static defaultProps = {
        testAutomationId: 'catalogGridDetails',
        close: null,
        shouldScrollIntoView: false
    };

    componentDidMount() {
        const {shouldScrollIntoView} = this.props;

        if (shouldScrollIntoView) {
            scrollElementIntoView(this.ref.current);
        }
    }

    ref = React.createRef();

    renderIcon() {
        return React.cloneElement(this.props.icon, {size: 40, isRound: true});
    }

    render() {
        const {
            colCount,
            index,
            children,
            testAutomationId,
            title,
            close,
            shouldScrollIntoView
        } = this.props;

        const titleNode = (
            <FlexBlock align={FlexBlock.CENTER}>
                {this.renderIcon()}
                <div className="rc-catalog-grid-details__title" data-test-automation-id="title">
                    {title}
                </div>
            </FlexBlock>
        );

        return (
            <InfoCard
                testAutomationId={testAutomationId}
                tipOffset={InfoCard.calculateTipPositionWithColumns(index, colCount)}
                title={titleNode}
                onClose={close}
                shouldScrollIntoView={shouldScrollIntoView}>
                {children}
            </InfoCard>
        );
    }
}
