import { useEffect, useRef } from 'react'

import noop from 'lodash/noop'

import { useToggle } from 'hooks'

type Args = {
  callback: () => void,
  intervalDuration: number,
  startImmediate?: boolean,
}

export const useInterval = ({
  callback = noop,
  intervalDuration,
  startImmediate = true,
}: Args) => {
  const {
    close: stop,
    isOpen: isRunning,
    open: start,
  } = useToggle(startImmediate)
  const savedCallback = useRef(callback)

  useEffect(() => {
    savedCallback.current = callback
  }, [callback])

  useEffect(() => {
    if (!isRunning) return undefined

    const id = setInterval(savedCallback.current, intervalDuration)
    return () => clearInterval(id)
  }, [isRunning, intervalDuration])

  return { start, stop }
}
