import { ReactNode, useState, useRef, useEffect } from "react";
import { createPortal } from "react-dom";

interface TooltipProps {
  children: ReactNode;
  text: string;
  placement?: "top" | "bottom" | "left" | "right";
  className?: string;
}

export const Tooltip: React.FC<TooltipProps> = ({
  children,
  text,
  placement = "top",
  className = "",
}) => {
  const [isVisible, setIsVisible] = useState(false);
  const triggerRef = useRef<HTMLDivElement>(null);
  const tooltipRef = useRef<HTMLSpanElement>(null);

  const getPositionStyle = () => {
    if (!triggerRef.current) return {};
    
    const triggerRect = triggerRef.current.getBoundingClientRect();
    
    let top = 0;
    let left = 0;
    let transform = "";

    switch (placement) {
      case "top":
        top = triggerRect.top - 8; // Will be adjusted by transform
        left = triggerRect.left + triggerRect.width / 2;
        transform = "translate(-50%, -100%)";
        break;
      case "bottom":
        top = triggerRect.bottom + 8;
        left = triggerRect.left + triggerRect.width / 2;
        transform = "translateX(-50%)";
        break;
      case "left":
        top = triggerRect.top + triggerRect.height / 2;
        left = triggerRect.left - 8;
        transform = "translate(-100%, -50%)";
        break;
      case "right":
        top = triggerRect.top + triggerRect.height / 2;
        left = triggerRect.right + 8;
        transform = "translateY(-50%)";
        break;
    }

    return {
      top: `${top}px`,
      left: `${left}px`,
      transform,
    };
  };

  useEffect(() => {
    if (isVisible && tooltipRef.current) {
      // Force a re-render to update position after tooltip is mounted
      const timeout = setTimeout(() => {
        if (tooltipRef.current) {
          tooltipRef.current.style.visibility = 'visible';
        }
      }, 0);
      return () => clearTimeout(timeout);
    }
  }, [isVisible]);

  return (
    <>
      <div
        ref={triggerRef}
        className={`relative inline-flex ${className}`}
        onMouseEnter={() => setIsVisible(true)}
        onMouseLeave={() => setIsVisible(false)}
      >
        {children}
      </div>
      {isVisible &&
        createPortal(
          <span
            ref={tooltipRef}
            className="fixed z-[999999] px-3 py-1.5 text-xs font-medium text-white bg-gray-900 rounded-lg pointer-events-none whitespace-nowrap"
            style={getPositionStyle()}
          >
            {text}
            {/* Arrow */}
            <span
              className={`absolute ${
                placement === "top"
                  ? "top-full left-1/2 -translate-x-1/2 -mt-1 w-0 h-0 border-l-[6px] border-l-transparent border-r-[6px] border-r-transparent border-t-[6px] border-t-gray-900"
                  : placement === "bottom"
                  ? "bottom-full left-1/2 -translate-x-1/2 -mb-1 w-0 h-0 border-l-[6px] border-l-transparent border-r-[6px] border-r-transparent border-b-[6px] border-b-gray-900"
                  : placement === "left"
                  ? "left-full top-1/2 -translate-y-1/2 -ml-1 w-0 h-0 border-t-[6px] border-t-transparent border-b-[6px] border-b-transparent border-l-[6px] border-l-gray-900"
                  : "right-full top-1/2 -translate-y-1/2 -mr-1 w-0 h-0 border-t-[6px] border-t-transparent border-b-[6px] border-b-transparent border-r-[6px] border-r-gray-900"
              }`}
            />
          </span>,
          document.body
        )}
    </>
  );
};

