import { ISpell } from '@rpg-engine/shared';
import React, { useRef, useState } from 'react';
import { MobileSpellTooltip } from './MobileSpellTooltip';
import { MagicTooltip } from './SpellTooltip';

interface ISpellInfoWrapperProps {
  spell: ISpell;
  children: React.ReactNode;
  scale?: number;
  holdTouchDuration?: number; // New prop for hold touch duration
}

export const SpellInfoWrapper: React.FC<ISpellInfoWrapperProps> = ({
  children,
  spell,
  scale,
  holdTouchDuration = 500, // Default hold duration to 500ms
}) => {
  const [isTooltipVisible, setIsTooltipVisible] = useState(false);
  const [isTooltipMobileVisible, setIsTooltipMobileVisible] = useState(false);
  const touchTimeoutRef = useRef<NodeJS.Timeout | null>(null);

  const handleTouchStart = () => {
    touchTimeoutRef.current = setTimeout(() => {
      setIsTooltipMobileVisible(true);
      setIsTooltipVisible(false);
    }, holdTouchDuration);
  };

  const handleTouchEnd = () => {
    if (touchTimeoutRef.current) {
      clearTimeout(touchTimeoutRef.current);
      touchTimeoutRef.current = null;
    }
  };

  return (
    <div
      onMouseEnter={() => {
        if (!isTooltipMobileVisible) setIsTooltipVisible(true);
      }}
      onMouseLeave={setIsTooltipVisible.bind(null, false)}
      onTouchStart={handleTouchStart}
      onTouchEnd={handleTouchEnd}
    >
      {children}

      {isTooltipVisible && !isTooltipMobileVisible && (
        <MagicTooltip spell={spell} />
      )}
      {isTooltipMobileVisible && (
        <MobileSpellTooltip
          closeTooltip={() => {
            setIsTooltipMobileVisible(false);
            console.log('close');
          }}
          spell={spell}
          scale={scale}
        />
      )}
    </div>
  );
};