import React, { useState } from 'react';
import PropTypes from 'prop-types';
import ReactTooltip from 'react-tooltip';
import { createNamespace } from '../../tools/namingTools';
// IMPORTANT: (s)css should be imported after other atoms/components
import './styles/Tooltip.scss';

const n = createNamespace('Tooltip');

const TooltipComponent = ({
    id,
    effect,
    children,
    position,
    placeholder,
    className: extraClass,
    backgroundColor
}) => {
    const [isVisible, setIsVisible] = useState(false);

    if (!children || React.Children.count(children) !== 1) {
        return null;
    }

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

            return (
                <>
                    <span {...props}>{child}</span>
                    <ReactTooltip
                        place={position}
                        effect={effect}
                        id={id}
                        wrapper="span"
                        ariaHaspopup="true"
                        backgroundColor={backgroundColor}
                        clickable
                        afterShow={() => setIsVisible(true)}
                        afterHide={() => setIsVisible(false)}
                        aria-hidden={!isVisible && 'true'}
                        {...n('overlay').props}
                    >
                        <span>{placeholder}</span>
                    </ReactTooltip>
                </>
            );
        }

        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
    ]),
    className: PropTypes.string
};

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

export default TooltipComponent;
