import {
  Box,
  Tooltip as RadixTooltip,
  type TooltipProps as RadixTooltipProps,
} from '@radix-ui/themes';
import { useCallback, useState } from 'react';
import { useUIState } from '@/context/ui-state-provider';

export function Tooltip({
  children,
  ...props
}: RadixTooltipProps): React.ReactElement {
  const { isMobile } = useUIState();
  const [open, setOpen] = useState<boolean>(props.defaultOpen ?? false);

  const onOpenChange = useCallback(
    (e: boolean) => {
      if (isMobile) return;
      setOpen(e);
    },
    [isMobile]
  );

  const onClick = useCallback(
    (e: React.MouseEvent<HTMLDivElement>) => {
      if (!isMobile) return;
      e.preventDefault();
      setOpen((p) => !p);
    },
    [isMobile]
  );

  return (
    <RadixTooltip
      delayDuration={isMobile ? props.delayDuration : 0}
      onOpenChange={onOpenChange}
      open={open}
      {...props}
    >
      <Box asChild onClick={onClick}>
        {children}
      </Box>
    </RadixTooltip>
  );
}
