import React, { useEffect, useRef, useState } from 'react';

interface InfoTooltipProps {
  text: string;
}

/**
 * Small "i" badge that toggles a tooltip on click. Closes on outside click
 * or Escape.
 *
 * @param {InfoTooltipProps} props
 * @return {React.ReactElement}
 */
export default function InfoTooltip({ text }: InfoTooltipProps) {
  const [open, setOpen] = useState<boolean>(false);
  const popoverRef = useRef<HTMLDivElement | null>(null);

  useEffect(() => {
    if (!open) return;
    const handleOutside = (event: MouseEvent): void => {
      if (
        popoverRef.current &&
        event.target instanceof Node &&
        !popoverRef.current.contains(event.target)
      ) {
        setOpen(false);
      }
    };
    const handleEscape = (event: KeyboardEvent): void => {
      if (event.key === 'Escape') setOpen(false);
    };
    document.addEventListener('mousedown', handleOutside);
    document.addEventListener('keydown', handleEscape);
    return () => {
      document.removeEventListener('mousedown', handleOutside);
      document.removeEventListener('keydown', handleEscape);
    };
  }, [open]);

  return (
    <span className="relative inline-flex">
      <button
        type="button"
        aria-label="More info"
        aria-expanded={open}
        onClick={() => setOpen(value => !value)}
        className="flex h-4 w-4 cursor-pointer items-center justify-center rounded-full border border-gray-300 text-[9px] font-semibold text-gray-500 hover:border-[#B7007C] hover:text-[#B7007C]"
      >
        i
      </button>
      {open && (
        <div
          ref={popoverRef}
          role="dialog"
          className="absolute left-1/2 top-full z-50 mt-2 w-[260px] -translate-x-1/2 rounded-xl border border-gray-200 bg-white p-3 text-[11px] leading-relaxed text-gray-700 shadow-lg"
        >
          {text}
        </div>
      )}
    </span>
  );
}
