import YouTube from 'react-youtube'

import { useMatchPageStore } from 'features/MatchPage/store'
import { FiltersPopup } from 'features/MatchSidePlaylists/components/FiltersPopup'

import { PlayerWrapper } from '../../styled'
import { useVideoPlayer, Props } from '../../hooks'

export const YoutubePlayer = (props: Props) => {
  const { isOpenFiltersPopup, profile } = useMatchPageStore()

  const {
    onMouseMove,
    onPlayerClick,
    onTouchEnd,
    onTouchStart,
    playing,
    sizeOptions: {
      height,
      width,
    },
    wrapperRef,
  } = useVideoPlayer(props)

  const youtube_link = profile?.youtube_link || ''
  const key = youtube_link.slice(32, youtube_link.length)

  return (
    <PlayerWrapper
      ref={wrapperRef}
      playing={playing}
      onClick={onPlayerClick}
      onMouseMove={onMouseMove}
      onTouchStart={onTouchStart}
      onTouchEnd={onTouchEnd}
    >
      {isOpenFiltersPopup && <FiltersPopup />}
      <YouTube
        videoId={key}
        opts={{
          height: String(height),
          playerVars: {
            autoplay: 1,
            modestbranding: 1,
          },
          width: String(width),
        }}
      />
    </PlayerWrapper>
  )
}
