import { h } from 'preact'
import { useEffect, useRef, useState } from 'preact/hooks'
import {
  instanceOf,
  number,
  object,
  shape,
  string,
} from 'prop-types'
import 'regenerator-runtime/runtime'
import { PeerTubePlayer } from '@peertube/embed-api'

import Chat from '../Chat'
import Overlay from '../VideoOverlay'
import { VideoWrapper, Iframe, PlayButton } from './styles'
import config from '../../data/config'
import { useToggle } from '../../hooks/utility'

const Video = ({ video, org, setInfoActive }) => {
  const [isPlaying, setPlaying] = useState(false)
  const [isFullscreen, toggleIsFullscreen] = useToggle(false)
  const videoiFrame = useRef(null)
  const overlayTimeout = useRef(null)
  const [videoReady, setVideoReady] = useState(false)
  const [overlayActive, setOverlayActiveState] = useState(true)
  const ptVideo = useRef(null)

  useEffect(() => {
    const setVideo = async () => {
      const player = new PeerTubePlayer(videoiFrame.current)
      await player.ready

      ptVideo.current = player
      player.setVolume(100)
      setVideoReady(true)
    }
    setVideo()
  }, [])

  const playVideo = () => {
    const { current: player } = ptVideo
    if (!videoReady) return

    setPlaying(true)
    try {
      player.play()
    } catch (error) {
      console.log({ error })
      setOverlayActiveState(true)
      setPlaying(false)
    }
  }
  const pauseVideo = () => {
    const { current: player } = ptVideo
    setPlaying(false)
    setOverlayActiveState(true)
    try {
      player.pause()
    } catch (error) {
      console.log({ error })
      setPlaying(true)
      setOverlayActiveState(false)
    }
  }

  const toggleVideo = () => {
    if (isPlaying) {
      pauseVideo()
    } else {
      playVideo()
    }
  }

  const toggleFullscreen = () => {
    toggleIsFullscreen()
    if (!document.fullscreenElement) {
      document.documentElement.requestFullscreen()
    } else if (document.exitFullscreen) {
      document.exitFullscreen()
    }
  }

  const handleKeyPress = keyCode => {
    if (keyCode === 32) {
      // key == 'space'
      toggleVideo()
    }
    if (keyCode === 70) {
      // key == 'f'
      toggleFullscreen()
    }
  }

  useEffect(() => {
    window.addEventListener('keydown', ({ keyCode }) => handleKeyPress(keyCode))

    return () =>
      window.removeEventListener('keydown', ({ keyCode }) =>
        handleKeyPress(keyCode)
      )
  }, [])

  const activateOverlay = () => {
    clearTimeout(overlayTimeout.current)
    setOverlayActiveState(true)

    overlayTimeout.current = setTimeout(
      () => setOverlayActiveState(false),
      2000
    )
  }

  return (
    <VideoWrapper
      $active={overlayActive || !isPlaying}
      onMouseMove={activateOverlay}
    >
      <Overlay
        onClick={toggleVideo}
        active={overlayActive || !isPlaying}
        title={video.title}
        setInfoActive={setInfoActive}
        onClickFullscreen={toggleFullscreen}
        isFullscreen={isFullscreen}
      />
      {!isPlaying && <PlayButton />}
      <Iframe
        sandbox="allow-same-origin allow-scripts allow-popups"
        src={`${config.peertube_root}${video.embedPath}?api=1&controls=false&vq=hd1080`}
        frameborder="0"
        allowfullscreen
        allow="autoplay"
        ref={videoiFrame}
      />
      <Chat overlayActive={overlayActive} />
    </VideoWrapper>
  )
}

Video.propTypes = {
  video: shape({
    account: object,
    category: object,
    channel: object,
    description: string,
    duration: number,
    embedPath: string,
    end: instanceOf(Date),
    id: string,
    language: object,
    previewPath: string,
    start: instanceOf(Date),
    state: object,
    title: 'Testing a livesteam :)',
    videoUrl: string,
    views: number,
  }),
  title: string.isRequired,
  org: string,
}

export default Video
