import type { ReactNode } from 'react';
import { cva, VariantProps } from 'class-variance-authority';
import * as RadixTooltip from '@radix-ui/react-tooltip';

type TooltipStylesProps = VariantProps<typeof tooltipStyles>;
const tooltipStyles = cva(
  'c-tooltip-content data-[state=delayed-open]:data-[side=top]:animate-slideDownAndFade data-[state=delayed-open]:data-[side=right]:animate-slideLeftAndFade data-[state=delayed-open]:data-[side=left]:animate-slideRightAndFade data-[state=delayed-open]:data-[side=bottom]:animate-slideUpAndFade',
  {
    variants: {
      variant: {
        info: 'c-tooltip-info',
        warning: 'c-tooltip-warning',
        error: 'c-tooltip-error',
        success: 'c-tooltip-success',
      },
    },
    defaultVariants: {
      variant: 'info',
    },
  },
);

type TooltipProps = TooltipStylesProps &
  Partial<Pick<RadixTooltip.TooltipContentProps, 'side'>> & {
    children: ReactNode;
    content: ReactNode;
    delayDuration?: number;
    align?: 'start' | 'center' | 'end';
    defaultOpen?: boolean;
  };

export function Tooltip({
  variant,
  children,
  content,
  side = 'top',
  align = 'center',
  defaultOpen = false,
  delayDuration = 800,
}: TooltipProps) {
  return (
    <RadixTooltip.Provider delayDuration={delayDuration}>
      <RadixTooltip.Root defaultOpen={defaultOpen}>
        <RadixTooltip.Trigger asChild>{children}</RadixTooltip.Trigger>
        <RadixTooltip.Portal>
          <RadixTooltip.Content align={align} sideOffset={5} side={side} className={tooltipStyles({ variant })}>
            <RadixTooltip.Arrow className="c-tooltip-arrow" />
            {content}
          </RadixTooltip.Content>
        </RadixTooltip.Portal>
      </RadixTooltip.Root>
    </RadixTooltip.Provider>
  );
}
