import { Fragment, useState } from 'react'

import isEmpty from 'lodash/isEmpty'

import type { TCircleAnimation } from 'features/CircleAnimationBar'
import { initialCircleAnimation } from 'features/CircleAnimationBar'
import { useMatchPageStore } from 'features/MatchPage/store'
import { StreamPlayer } from 'features/StreamPlayer'
import { YoutubePlayer } from 'features/StreamPlayer/components/YoutubePlayer'
import { MatchSidePlaylists } from 'features/MatchSidePlaylists'

import { Container } from '../../styled'

import { useLiveMatch } from './hooks'
import { MatchDescription } from '../MatchDescription'

export const LiveMatch = () => {
  const [circleAnimation, setCircleAnimation] = useState<TCircleAnimation>(initialCircleAnimation)

  const {
    profile,
    selectedPlaylist,
  } = useMatchPageStore()

  const {
    chapters,
    onDurationChange,
    onPlayerProgressChange,
    onPlayingChange,
    onPlaylistSelect,
    resume,
    streamUrl,
  } = useLiveMatch()
  return (
    <Fragment>
      <Container>
        {profile?.youtube_link ? (
          <YoutubePlayer
            chapters={chapters}
            onPlayingChange={onPlayingChange}
            isLive={profile.live}
            onProgressChange={onPlayerProgressChange}
            resumeFrom={resume}
            url={streamUrl}
            setCircleAnimation={setCircleAnimation}
          />
        ) : (
          !isEmpty(chapters) && (
            <StreamPlayer
              setCircleAnimation={setCircleAnimation}
              onDurationChange={onDurationChange}
              onPlayingChange={onPlayingChange}
              onProgressChange={onPlayerProgressChange}
              isLive={!!profile?.live}
              resumeFrom={resume}
              chapters={chapters}
            />
          )
        )}
        <MatchDescription />
      </Container>

      <MatchSidePlaylists
        setCircleAnimation={setCircleAnimation}
        circleAnimation={circleAnimation}
        onSelect={onPlaylistSelect}
        selectedPlaylist={selectedPlaylist}
      />
    </Fragment>
  )
}
