import React from 'react';
import PropTypes from 'prop-types';
import {CatalogItemIcon} from './CatalogItemIcon';

import {Icon} from '../Icon';
import {FlexBlock} from '../flexBlock/FlexBlock';
import {scrollEelementIntoView} from '../../utils/functions';

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

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

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

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

    ref = React.createRef();

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

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

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

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

        return (
            <div
                ref={this.ref}
                className="rc-catalog-grid-details"
                data-test-automation-id={testAutomationId}>
                <div
                    style={{left: `${100 / colCount * (index % colCount + 0.5)}%`}}
                    className="rc-catalog-grid-details__tip"
                />
                <FlexBlock
                    justify={FlexBlock.SPACE_BETWEEN}
                    className="rc-catalog-grid-details__header">
                    <FlexBlock align={FlexBlock.CENTER}>
                        {this.renderIcon()}
                        <div
                            className="rc-catalog-grid-details__title"
                            data-test-automation-id="title">
                            {title}
                        </div>
                    </FlexBlock>
                    <button
                        onClick={close}
                        className="rc-catalog-grid-details__close"
                        data-test-automation-id="closeButton">
                        <Icon name="close" />
                    </button>
                </FlexBlock>
                <div data-test-automation-id="gridDetailsChildren">{children}</div>
            </div>
        );
    }
}
