import React, { useRef, useState } 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,
    className: extraClass,
    backgroundColor
}) => {
    const buttonRef = useRef();
    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,
                onFocus: () => ReactTooltip.show(buttonRef.current),
                onBlur: () => ReactTooltip.hide(buttonRef.current)
            };

            return (
                <>
                    <button {...props} type="button" ref={buttonRef}>{child}</button>
                    <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;
