import React from 'react';
import { PopperPlacementType } from "@mui/material";
import { RichTooltip } from "./tooltip";

interface Props {
    className?: string;
    flip?: boolean,
    preventOverflow?: boolean,
    content: React.ReactElement | (() => React.ReactElement);
    children: React.ReactElement;
    disabled?: boolean;
    arrow?: boolean;
    placement?: PopperPlacementType;
}

export const TouchTooltip: React.FC<Props> = ({
    className,
    flip = true,
    preventOverflow = true,
    placement,
    arrow,
    content,
    children,
    disabled
}) => {
    const [open, setOpen] = React.useState(false);

    if (disabled) {
        return React.cloneElement(children, { ...children.props, disabled: true });
    }

    const existingOnClick = children.props.onClick;
    const newOnClick = (e: MouseEvent) => {
        setOpen(!open);
        existingOnClick && existingOnClick(e);
    }

    const contentNode = typeof content === "function" ? content() : content;

    return (
        <RichTooltip
            className={className}
            flip={flip}
            preventOverflow={preventOverflow}
            open={!!open}
            onClose={() => setOpen(false)}
            arrow={arrow}
            placement={placement}
            content={contentNode}
        >
            {React.cloneElement(children, { ...children.props, onClick: newOnClick })}
        </RichTooltip>
    );
}