import { ISpell } from '@rpg-engine/shared';
import React, { useEffect, useRef } from 'react';
import styled from 'styled-components';
import ModalPortal from '../../Abstractions/ModalPortal';
import { SpellInfoDisplay } from './SpellInfoDisplay';

export interface IMagicTooltipProps {
  spell: ISpell;
}

const offset = 20;

export const MagicTooltip: React.FC<IMagicTooltipProps> = ({ spell }) => {
  const ref = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const { current } = ref;

    if (current) {
      const handleMouseMove = (event: MouseEvent) => {
        const { clientX, clientY } = event;

        // Adjust the position of the tooltip based on the mouse position
        const rect = current.getBoundingClientRect();

        const tooltipWidth = rect.width;
        const tooltipHeight = rect.height;
        const isOffScreenRight =
          clientX + tooltipWidth + offset > window.innerWidth;
        const isOffScreenBottom =
          clientY + tooltipHeight + offset > window.innerHeight;
        const x = isOffScreenRight
          ? clientX - tooltipWidth - offset
          : clientX + offset;
        const y = isOffScreenBottom
          ? clientY - tooltipHeight - offset
          : clientY + offset;

        current.style.transform = `translate(${x}px, ${y}px)`;
        current.style.opacity = '1';
      };

      window.addEventListener('mousemove', handleMouseMove);

      return () => {
        window.removeEventListener('mousemove', handleMouseMove);
      };
    }

    return;
  }, []);

  return (
    <ModalPortal>
      <Container ref={ref}>
        <SpellInfoDisplay spell={spell} />
      </Container>
    </ModalPortal>
  );
};

const Container = styled.div`
  position: absolute;
  z-index: 100;
  pointer-events: none;
  left: 0;
  top: 0;
  opacity: 0;
  transition: opacity 0.08s;
`;
