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

    if (startImmediate) savedCallback.current()

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

  return { start, stop }
}
