import { Fragment, h } from 'preact'
import { useEffect, useRef } from 'preact/hooks'
import { PeerTubePlayer } from '@peertube/embed-api'
import { string } from 'prop-types'
import Link from '../Link'
import { Label } from '../Text'
import strings from '../../data/strings'
import { Box, Img, Iframe } from './styles'
import { colours, textSizes } from '../../assets/theme'
import { Row } from '../Flex'
import CrossSvg from '../Svg/Cross'
import { useUiStore } from '../../store'
import { getLabel } from './helpers'
import Chevron from '../Svg/Chevron'
// import { useEventApi } from '../../hooks/data'

const StreamPreview = ({ stream, isLive, ...rest }) => {
  const currentLanguage = 'en'
  const videoiFrame = useRef(null)
  const ptVideo = useRef(null)
  const { isMinimized, toggleMinimized } = useUiStore(store => ({ isMinimized: store.streamPreviewMinimized, toggleMinimized: store.toggleStreamPreviewMinimized }))


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

      ptVideo.current = player
      player.setVolume(0)
      player.play()
    }
    if (isLive) {
      setupAndPlayVideo()
    }
  }, [isLive, isMinimized])

  return stream ? (
    <Box isMinimized={isMinimized}>
      <Row justify="space-between">
        <Label colour={colours.midnightDarker} size={textSizes.lg}>{getLabel(stream, isLive, isMinimized)}</Label>
        {isMinimized ? <Chevron colour={colours.midnightDarker} size={14} onClick={toggleMinimized} /> : <CrossSvg colour={colours.midnightDarker} size={16} onClick={toggleMinimized} />}
      </Row>
      {!isMinimized ?
        <Fragment>
          {isLive ?
            <Iframe
              width="560"
              height="315"
              sandbox="allow-same-origin allow-scripts allow-popups"
              autoplay="autoplay"
              muted="muted"
              src={`https://tv.undersco.re${stream.embedPath}?api=1&controls=false`}
              frameBorder="0"
              allowFullScreen
              ref={videoiFrame}
            />
            : <Img src={stream.image} />}
        </Fragment> : null}
    </Box>
  ) : null
}


export default StreamPreview
