import React, { useEffect, useState } from 'react';
import type { ReactNode } from 'react';
import { useFloating, offset } from '@floating-ui/react-dom';
import type { Placement, Strategy } from '@floating-ui/react-dom';

type Props = {
  children: ReactNode;
  tooltipContent: ReactNode;
  tooltipStrategy?: Strategy;
  placement?: Placement;
  id: string;
};

export function TooltipWrapper({
  children,
  tooltipContent,
  tooltipStrategy,
  placement,
  id,
}: Props) {
  const [showTooltip, setShowTooltip] = useState(false);

  const { x, y, reference, floating, strategy, update } = useFloating({
    placement,
    middleware: [offset(10)],
    strategy: tooltipStrategy,
  });

  function showTooltipFunc() {
    setShowTooltip(true);
  }

  function hideTooltipFunc() {
    setShowTooltip(false);
  }

  function onKeyDown(event: KeyboardEvent) {
    if (event.code === 'Escape') {
      hideTooltipFunc();
    }
  }

  useEffect(() => {
    update();
    if (showTooltip) {
      document.addEventListener('keydown', onKeyDown);
    } else {
      document.removeEventListener('keydown', onKeyDown);
    }

    return () => {
      document.removeEventListener('keydown', onKeyDown);
    };
  }, [showTooltip]);

  return (
    <>
      <span
        ref={reference}
        onMouseEnter={showTooltipFunc}
        onMouseLeave={hideTooltipFunc}
        onFocus={showTooltipFunc}
        onBlur={hideTooltipFunc}
      >
        {children}
      </span>
      <div
        role="tooltip"
        ref={floating}
        style={{
          display: showTooltip ? 'block' : 'none',
          position: strategy,
          top: y ?? '',
          left: x ?? '',
        }}
        className="rounded bg-neutral-20 py-1 px-2 text-white text-sm"
        id={id}
      >
        {tooltipContent}
      </div>
    </>
  );
}

TooltipWrapper.defaultProps = {
  tooltipStrategy: 'fixed',
  placement: 'top',
};
