import { JSX, ParentComponent, Show, createSignal, splitProps } from "solid-js";

interface TooltipProps {
  content: string | JSX.Element;
  placement?: "top" | "bottom" | "left" | "right";
  delay?: number;
  children: JSX.Element;
}

export const Tooltip: ParentComponent<TooltipProps> = (props) => {
  const [local] = splitProps(props, ["content", "placement", "delay", "children"]);
  const [isVisible, setIsVisible] = createSignal(false);
  const [timeoutId, setTimeoutId] = createSignal<number | null>(null);

  const placementClasses = {
    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 = {
    top: "top-full left-1/2 -translate-x-1/2 -mt-1 border-t-canvas-elevated",
    bottom: "bottom-full left-1/2 -translate-x-1/2 -mb-1 border-b-canvas-elevated",
    left: "left-full top-1/2 -translate-y-1/2 -ml-1 border-l-canvas-elevated",
    right: "right-full top-1/2 -translate-y-1/2 -mr-1 border-r-canvas-elevated",
  };

  const handleMouseEnter = () => {
    const id = window.setTimeout(() => {
      setIsVisible(true);
    }, local.delay || 200);
    setTimeoutId(id);
  };

  const handleMouseLeave = () => {
    const id = timeoutId();
    if (id) {
      window.clearTimeout(id);
      setTimeoutId(null);
    }
    setIsVisible(false);
  };

  return (
    <div 
      class="relative inline-flex"
      onMouseEnter={handleMouseEnter}
      onMouseLeave={handleMouseLeave}
      onFocus={handleMouseEnter}
      onBlur={handleMouseLeave}
    >
      {local.children}
      
      <Show when={isVisible()}>
        <div
          class={[
            "absolute z-50 px-3 py-2",
            "bg-canvas-elevated text-ink text-sm",
            "font-sans rounded-lg shadow-lg border border-border",
            "animate-scale-in origin-center",
            placementClasses[local.placement || "top"],
          ].join(" ")}
          role="tooltip"
        >
          {local.content}
          
          {/* Arrow */}
          <div
            class={[
              "absolute w-2 h-2 rotate-45",
              "bg-canvas-elevated border border-border",
              arrowClasses[local.placement || "top"],
            ].join(" ")}
          />
        </div>
      </Show>
    </div>
  );
};
