import React from 'react';
import PropTypes from 'prop-types';
import ReactTooltip from 'react-tooltip';
import { createNamespace } from '../../tools/namingTools';
import './styles/Tooltip.scss';

const n = createNamespace('Tooltip');

const TooltipComponent = ({
    id,
    effect,
    children,
    position,
    placeholder,
    backgroundColor
}) => {
    if (!children || React.Children.count(children) !== 1) {
        return null;
    }

    const renderChild = child => {
        if (placeholder) {
            const props = {
                'data-tip': placeholder,
                'data-for': id
            };

            return (
                <React.Fragment>
                    {typeof child === 'string' ? <span {...props} {...n('text').props}>{child}</span> : React.cloneElement(child, props)}
                    <ReactTooltip
                        place={position}
                        effect={effect}
                        id={id}
                        wrapper="span"
                        ariaHaspopup="true"
                        backgroundColor={backgroundColor}
                        {...n('overlay').props}
                    >
                        {placeholder}
                    </ReactTooltip>
                </React.Fragment>
            );
        }

        return child;
    };

    return React.Children.map(children, renderChild);
};

TooltipComponent.propTypes = {
    id: PropTypes.string.isRequired,
    position: PropTypes.oneOf(['top', 'right', 'bottom', 'left']),
    effect: PropTypes.oneOf(['float', 'solid']),
    backgroundColor: PropTypes.string,
    placeholder: PropTypes.oneOfType([
        PropTypes.string,
        PropTypes.object
    ])
};

TooltipComponent.defaultProps = {
    placeholder: null,
    id: 'global',
    position: 'top',
    effect: 'solid',
    backgroundColor: '#414141'
};

export default TooltipComponent;
