import React, { useEffect, useRef, useState } from 'react';
import { SilkeTooltip, SilkeTooltipProps, SilkeTooltipSize } from './silke-tooltip';
import styles from './silke-tooltip.scss';

type SilkeDefinitionTooltipProps = {
  children: React.ReactNode;
  style?: React.CSSProperties;
  className?: string;
  show?: boolean;
  size?: SilkeTooltipSize;
  kind?: 'default' | 'info';
  tooltip: React.ReactNode;
  hideBorder?: boolean;
} & Omit<SilkeTooltipProps, 'children' | 'anchor' | 'show'>;

/**
 * Wrap some text in this to show extra context
 */
export function SilkeDefinitionTooltip({
  className,
  children,
  show,
  tooltip,
  style,
  size,
  anchorOrigin,
  hideBorder,
  ...rest
}: SilkeDefinitionTooltipProps) {
  const ref = useRef<HTMLElement>(null);
  const [isShowing, setShowing] = useState(show ?? false);
  useEffect(() => {
    const el = ref.current;
    if (el) {
      el.onmouseover = () => setShowing(true);
      el.onmouseleave = () => setShowing(false);
    }
  }, []);

  const cl = [styles.definitionTooltip];
  if (className) cl.push(className);
  if (hideBorder) cl.push(styles.noBorder);
  return (
    <>
      <span className={cl.join(' ')} ref={ref} style={style}>
        {children}
      </span>

      {ref && (
        <SilkeTooltip
          {...rest}
          anchor={ref}
          size={size || 'tiny'}
          show={show === undefined ? isShowing : show}
          anchorOrigin={anchorOrigin || 'bottom-right'}
        >
          {tooltip}
        </SilkeTooltip>
      )}
    </>
  );
}
