import * as React from 'react';
import { useTooltip } from './useTooltip';
import { TooltipContent } from './TooltipContent';
import type { TooltipProps } from './types';

export function Tooltip({
  content,
  children,
  position = 'top',
  trigger = 'hover',
  delay = 200,
  showArrow = true,
  maxWidth,
  disabled = false,
  className,
}: TooltipProps) {
  const {
    visible,
    isMounted,
    calculatedPosition,
    tooltipStyle,
    wrapperRef,
    tooltipRef,
    triggerProps,
  } = useTooltip(position, trigger, delay, disabled);

  if (disabled) {
    return <>{children}</>;
  }

  const isHover = trigger === 'hover';
  const wrapperProps = isHover ? triggerProps : {};
  const child =
    !isHover &&
    React.isValidElement(children) &&
    React.Children.only(children)
      ? React.cloneElement(children, triggerProps as React.HTMLAttributes<HTMLElement>)
      : children;

  return (
    <div ref={wrapperRef} className="relative inline-block" {...wrapperProps}>
      {child}
      {isMounted && (
        <TooltipContent
          content={content}
          visible={visible}
          calculatedPosition={calculatedPosition}
          tooltipStyle={tooltipStyle}
          tooltipRef={tooltipRef}
          showArrow={showArrow}
          maxWidth={maxWidth}
          className={className}
        />
      )}
    </div>
  );
}
