import * as React from "react"
import { cn } from "../../../src/lib/utils"

type TooltipPosition = "top" | "bottom" | "left" | "right";

interface TooltipProps extends React.HTMLAttributes<HTMLDivElement> {
  text: string;
  position?: TooltipPosition;
  children: React.ReactNode;
}

const positionClasses: Record<TooltipPosition, string> = {
  top: "bottom-full left-1/2 -translate-x-1/2 mb-2",
  bottom: "top-full left-1/2 -translate-x-1/2 mt-2",
  left: "right-full top-1/2 -translate-y-1/2 mr-2",
  right: "left-full top-1/2 -translate-y-1/2 ml-2",
};

const arrowClasses: Record<TooltipPosition, string> = {
  top: "top-full left-1/2 -translate-x-1/2 border-t-gray-800 dark:border-t-white border-l-transparent border-r-transparent border-b-transparent",
  bottom: "bottom-full left-1/2 -translate-x-1/2 border-b-gray-800 dark:border-b-white border-l-transparent border-r-transparent border-t-transparent",
  left: "left-full top-1/2 -translate-y-1/2 border-l-gray-800 dark:border-l-white border-t-transparent border-b-transparent border-r-transparent",
  right: "right-full top-1/2 -translate-y-1/2 border-r-gray-800 dark:border-r-white border-t-transparent border-b-transparent border-l-transparent",
};

const Tooltip = React.forwardRef<HTMLDivElement, TooltipProps>(
  ({ text, position = "top", className, children, ...props }, ref) => {
    const [visible, setVisible] = React.useState<boolean>(false);

    return (
      <div
        ref={ref}
        className={cn("relative inline-flex", className)}
        onMouseEnter={() => setVisible(true)}
        onMouseLeave={() => setVisible(false)}
        {...props}
      >
        {children}

        {visible && (
          <div
            className={cn(
                "absolute z-[9999] whitespace-nowrap px-2.5 py-1.5 rounded-md text-xs font-medium pointer-events-none shadow-md",
                "bg-gray-800 text-white",                    // light mode
                "dark:bg-white dark:text-gray-900",          // dark mode
                positionClasses[position]
                )}
            >
            {text}
            <span className={cn("absolute border-4", arrowClasses[position])} />
          </div>
        )}
      </div>
    );
  }
);

Tooltip.displayName = "Tooltip";

export { Tooltip };
export type { TooltipProps, TooltipPosition };