import clsx from "clsx";
import { Tooltip as RTooltip } from "radix-ui";
import * as React from "react";
import { useNestableChild } from "../../hooks/useNestableChild";
import { ButtonContext } from "../Link";
import * as styles from "./styles.module.css";

export interface TooltipProps {
  "data-id": string;
  className?: string;
  asChild?: boolean;
  label: string;
  side: "top" | "bottom" | "left" | "right";
  align: "start" | "center" | "end";
  delayDuration?: number;
  showArrow?: boolean;
  children: React.ReactNode;
}

export const TooltipSymbol = Symbol("Tooltip");

export function Tooltip({
  className,
  showArrow = true,
  delayDuration,
  children,
  label,
  side,
  align,
  asChild,
  ...rest
}: TooltipProps) {
  if (!children) return null;
  let validChild = useNestableChild(children);
  return (
    <RTooltip.Provider delayDuration={delayDuration}>
      <RTooltip.Root>
        <ButtonContext value={true}>
          <RTooltip.Trigger asChild={validChild || asChild}>
            {children}
          </RTooltip.Trigger>
        </ButtonContext>
        <RTooltip.Portal>
          <RTooltip.Content
            className={clsx(className, styles.TooltipContent)}
            side={side}
            align={align}
            data-component="Tooltip$Brevity"
            {...rest}
          >
            {label}
            {showArrow ? (
              <RTooltip.Arrow className={styles.TooltipArrow} />
            ) : null}
          </RTooltip.Content>
        </RTooltip.Portal>
      </RTooltip.Root>
    </RTooltip.Provider>
  );
}
