import { useCallback, useState } from 'react';

interface ITapAndHoldProps {
  onHoldFn: (...args: any[]) => void;
  holdTime?: number;
}

export const useTapAndHold = ({ onHoldFn: onHold, holdTime = 500 }: ITapAndHoldProps) => {
  const [timer, setTimer] = useState<NodeJS.Timeout | null>(null);

  const start = useCallback(() => {
    const timeout = setTimeout(onHold, holdTime);
    setTimer(timeout);
  }, [onHold, holdTime]);

  const clear = useCallback(() => {
    if (timer) {
      clearTimeout(timer);
      setTimer(null);
    }
  }, [timer]);

  const bind = {
    onTouchStart: start,
    onTouchEnd: clear,
    onTouchCancel: clear,
  };

  return bind;
};
