import { TooltipDirection } from '@/models';

export const useTooltipHelper = () => {
  const _shiftTranslatePosition = (
    direction: TooltipDirection,
    tooltipElement: {
      right: number;
      left: number;
      top: number;
      bottom: number;
    },
    window: { width: number; height: number },
    translatePosition: { x: number; y: number },
  ) => {
    let shiftedX = translatePosition.x;
    let shiftedY = translatePosition.y;

    if (
      direction === TooltipDirection.Bottom ||
      direction === TooltipDirection.Top
    ) {
      // overflow left
      if (tooltipElement.left + translatePosition.x < 0)
        shiftedX = -tooltipElement.left;

      // overflow right
      if (tooltipElement.right + translatePosition.x > window.width)
        shiftedX = window.width - tooltipElement.right;
    }

    if (
      direction === TooltipDirection.Left ||
      direction === TooltipDirection.Right
    ) {
      // overflow top
      if (tooltipElement.top + translatePosition.y < 0)
        shiftedY = tooltipElement.top;

      // overflow bottom
      if (tooltipElement.bottom + translatePosition.y > window.height)
        shiftedY = window.height - tooltipElement.bottom;
    }

    return { shiftedX, shiftedY };
  };

  const _getTranslatePosition = (
    direction: TooltipDirection,

    anchorElement: { width: number; height: number },
    tooltipElement: {
      width: number;
      height: number;
    },
    margin = 5,
  ) => {
    switch (direction) {
      case TooltipDirection.Top:
        return {
          x: (anchorElement.width - tooltipElement.width) / 2,
          y: -tooltipElement.height - margin,
        };

      case TooltipDirection.Bottom:
        return {
          x: (anchorElement.width - tooltipElement.width) / 2,
          y: anchorElement.height + margin,
        };

      case TooltipDirection.Left:
        return {
          x: -tooltipElement.width - margin,
          y: (anchorElement.height - tooltipElement.height) / 2,
        };

      case TooltipDirection.Right:
        return {
          x: anchorElement.width + margin,
          y: (anchorElement.height - tooltipElement.height) / 2,
        };
    }
  };

  const getTooltipTranslatePosition = (
    direction: TooltipDirection,
    window: { width: number; height: number },
    anchorElement: { width: number; height: number },
    tooltipElement: {
      width: number;
      height: number;
      right: number;
      left: number;
      top: number;
      bottom: number;
    },
  ) => {
    const { x, y } = _getTranslatePosition(
      direction,
      anchorElement,
      tooltipElement,
    );

    let { shiftedX, shiftedY } = _shiftTranslatePosition(
      direction,
      tooltipElement,
      window,
      { x, y },
    );

    return {
      translateX: shiftedX,
      translateY: shiftedY,
    };
  };

  return {
    getTooltipTranslatePosition,
    _getTranslatePosition,
    _shiftTranslatePosition,
  };
};
