import React, { CSSProperties, HTMLAttributes, useEffect, useRef, useState } from "react";
import { Tooltip as Tooltip_, TooltipProps } from "antd";
import type { TooltipPlacement } from "antd/es/tooltip";


const DefaultStyle: CSSProperties = {
  overflow: "hidden",
  whiteSpace: "nowrap",
  textOverflow: "ellipsis",
  // backgroundColor: "red"
}

export default function ({ msg, defaultStyle, style, placement, children, ...rest }: { msg: string | JSX.Element, defaultStyle?: boolean, placement?: TooltipPlacement } & HTMLAttributes<any>) {
  const wrapper = useRef<HTMLDivElement>(null);
  const text = useRef<HTMLSpanElement>(null);
  const [toolTip, setToolTip] = useState(false);

  useEffect(() => {

    const wrapperRect = wrapper.current!.getBoundingClientRect(),
      textRect = text.current!.getBoundingClientRect();

    if (wrapperRect.width < textRect.width) {
      setToolTip(true);
    }
  }, [msg]);

  const _text = (
    <div
      ref={wrapper}
      style={defaultStyle ? { ...DefaultStyle, ...style } : style}
      {...rest}
    >
      <span ref={text}>{children ?? msg}</span>
      {/* {msg} */}
    </div>
  );

  if (toolTip) {
    return <Tooltip_ title={msg} placement={placement} /* color="#fff" overlayInnerStyle={{ color: '#000' }} */ >{_text}</Tooltip_>;
  } else {
    return _text;
  }
}

export const Tooltip = ({ children, color, ...props }: TooltipProps) => {
  return <Tooltip_ /* color="#fff" overlayInnerStyle={{ color: '#000' }} */ {...props} >{children}</Tooltip_>
}