import { useCallback, useMemo } from 'react'

import debounce from 'lodash/debounce'

import { useToggle } from 'hooks'

export const useControlsVisibility = (isFullscreen: boolean, playing: boolean) => {
  const {
    close: hideCenterControls,
    isOpen: centerControlsVisible,
    open: showCenterControls,
  } = useToggle(playing)

  const hideCenterDebounced = useMemo(() => (
    debounce(hideCenterControls, 2000)
  ), [hideCenterControls])

  const showCenter = useCallback(() => {
    if (playing) {
      showCenterControls()
      hideCenterDebounced()
    } else {
      showCenterControls()
    }
  }, [hideCenterDebounced, playing, showCenterControls])

  const {
    close: hideMainControls,
    isOpen: mainControlsVisible,
    open: showMainControls,
  } = useToggle(true)

  const hideDebounced = useMemo(
    () => debounce(hideMainControls, 3000),
    [hideMainControls],
  )

  const onMouseMove = () => {
    showMainControls()
    if (isFullscreen) {
      hideDebounced()
    }
  }

  return {
    centerControlsVisible,
    hideCenterControls,
    mainControlsVisible,
    onMouseEnter: showMainControls,
    onMouseLeave: hideMainControls,
    onMouseMove,
    onTouchEnd: hideDebounced,
    onTouchStart: showMainControls,
    showCenterControls: showCenter,
  }
}
