import { useEffect, useRef } from 'react'
import screenfull from 'screenfull'

import { isIOS } from 'config/userAgent'

import { useToggle } from 'hooks'

type IOSVideo = HTMLVideoElement & {
  webkitEnterFullscreen: () => void,
  webkitExitFullscreen: () => void,
}

const supportsFullscreen = (video: HTMLVideoElement | null): video is IOSVideo => Boolean(
  video
  && 'webkitEnterFullscreen' in video
  && 'webkitExitFullscreen' in video,
)

export const useFullscreen = (activePlayer: React.RefObject<HTMLVideoElement>) => {
  const wrapperRef = useRef<HTMLDivElement>(null)
  const {
    isOpen: isFullscreen,
    setIsOpen: setFullscreen,
  } = useToggle()

  useEffect(() => {
    if (!screenfull.isEnabled) return undefined
    const changeListener = () => {
      setFullscreen(screenfull.isEnabled && screenfull.isFullscreen)
    }
    screenfull.onchange(changeListener)

    return () => {
      if (screenfull.isEnabled) {
        screenfull.off('change', changeListener)
      }
    }
  }, [setFullscreen])

  const toggleFullscreen = () => {
    if (screenfull.isEnabled && wrapperRef.current) {
      screenfull.toggle(wrapperRef.current)
    }
  }

  const toggleIOSFullscreen = () => {
    const video = activePlayer?.current
    if (!video || !supportsFullscreen(video)) return

    if (isFullscreen) {
      video.webkitExitFullscreen()
    } else {
      video.webkitEnterFullscreen()
    }
  }

  const onFullscreenClick = () => {
    if (isIOS) {
      toggleIOSFullscreen()
    } else {
      toggleFullscreen()
    }
  }

  return {
    isFullscreen,
    onFullscreenClick,
    wrapperRef,
  }
}
