import type { RefObject } from 'react'
import { useState, useCallback } from 'react'

import once from 'lodash/once'

import { useEventListener } from 'hooks'

export const usePlayingState = (videoRef: RefObject<HTMLVideoElement>) => {
  const [playing, setPlaying] = useState(false)
  const [ready, setReady] = useState(false)

  const togglePlaying = useCallback(() => {
    setPlaying((isPlaying) => {
      const video = videoRef.current
      if (!ready || !video) return false

      const nextIsPlaying = !isPlaying
      if (nextIsPlaying) {
        video.play()
      } else {
        video.pause()
      }
      return nextIsPlaying
    })
  }, [videoRef, ready])

  const onReady = useCallback(once(() => {
    setReady(true)
  }), [])

  useEventListener({
    callback: onReady,
    event: 'canplay',
    ref: videoRef,
  })

  return {
    playing,
    ready,
    togglePlaying,
  }
}
