import { useEffect, RefObject } from "react";

export type SwipeDirection = "left" | "right" | "up" | "down";

interface SwipeCallbacks {
  onSwipeLeft?: () => void;
  onSwipeRight?: () => void;
  onSwipeUp?: () => void;
  onSwipeDown?: () => void;
}

interface UseSwipeOptions {
  minSwipeDistance?: number;
  maxSwipeTime?: number;
}

// Hook to detect swipe gestures on a given element
export function useSwipe(
  ref: RefObject<HTMLElement>,
  callbacks: SwipeCallbacks,
  options: UseSwipeOptions = {}
) {
  const { minSwipeDistance = 50, maxSwipeTime = 300 } = options;

  useEffect(() => {
    const element = ref.current;
    if (!element) return;

    let touchStartX = 0;
    let touchStartY = 0;
    let touchStartTime = 0;

    const handleTouchStart = (e: TouchEvent) => {
      const touch = e.touches[0];
      touchStartX = touch.clientX;
      touchStartY = touch.clientY;
      touchStartTime = Date.now();
    };

    const handleTouchEnd = (e: TouchEvent) => {
      const touch = e.changedTouches[0];
      const touchEndX = touch.clientX;
      const touchEndY = touch.clientY;
      const touchEndTime = Date.now();

      const deltaX = touchEndX - touchStartX;
      const deltaY = touchEndY - touchStartY;
      const deltaTime = touchEndTime - touchStartTime;

      // Check if the swipe was fast enough
      if (deltaTime > maxSwipeTime) return;

      // Determine if this is a horizontal or vertical swipe
      const absX = Math.abs(deltaX);
      const absY = Math.abs(deltaY);

      // Check if the swipe distance is long enough
      if (absX < minSwipeDistance && absY < minSwipeDistance) return;

      // Horizontal swipe
      if (absX > absY) {
        if (deltaX > 0) {
          callbacks.onSwipeRight?.();
        } else {
          callbacks.onSwipeLeft?.();
        }
      }
      // Vertical swipe
      else {
        if (deltaY > 0) {
          callbacks.onSwipeDown?.();
        } else {
          callbacks.onSwipeUp?.();
        }
      }
    };

    element.addEventListener("touchstart", handleTouchStart, { passive: true });
    element.addEventListener("touchend", handleTouchEnd, { passive: true });

    return () => {
      element.removeEventListener("touchstart", handleTouchStart);
      element.removeEventListener("touchend", handleTouchEnd);
    };
  }, [ref, callbacks, minSwipeDistance, maxSwipeTime]);
}
