import {
  RefObject,
  useEffect,
} from 'react'

import styled from 'styled-components/macro'

import { Icon } from 'features/Icon'
import { useAuthStore } from 'features/AuthStore'

const PipWrapper = styled.div`
  cursor: pointer;
  margin-left: 25px;
  margin-right: 25px;
  margin-top: 4px;
`

type PipProps = {
  videoRef: RefObject<HTMLVideoElement>,
}

export const PiP = ({ videoRef }: PipProps) => {
  const { user } = useAuthStore()
  const togglePip = async () => {
    try {
      if (
        document.pictureInPictureEnabled && videoRef.current !== document.pictureInPictureElement
      ) {
        await videoRef.current?.requestPictureInPicture()
      } else {
        await document.exitPictureInPicture()
      }
    } catch (err) {
      await document.exitPictureInPicture()
    }
  }

  useEffect(() => {
    const onVisibilityChange = async () => {
      if (
        document.hidden === true
        && document.pictureInPictureEnabled
        && videoRef.current !== document.pictureInPictureElement
        && videoRef.current?.hidden === false
        && !videoRef.current?.paused
        && document.visibilityState !== 'visible'
          && user
      ) {
        try {
          await videoRef.current?.requestPictureInPicture()
        } catch (error) { /* empty */ }
      }
      if (
        document.visibilityState === 'visible'
        && document.pictureInPictureEnabled
        && videoRef.current === document.pictureInPictureElement
      ) {
        try {
          await document.exitPictureInPicture()
        } catch (error) { /* empty */ }
      }
    }
    window.addEventListener('visibilitychange', onVisibilityChange)

    return () => window.removeEventListener('visibilitychange', onVisibilityChange)
  }, [videoRef, user])

  return (
    <PipWrapper id='match_video_pic_in_pic'>
      <Icon refIcon='PiP' onClick={togglePip} />
    </PipWrapper>
  )
}
