import { Fragment } from 'react'

import isEmpty from 'lodash/isEmpty'

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

import { isMobileDevice } from 'config/userAgent'

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

import { useLiveMatch } from './hooks'
import { TournamentData } from '../../types'
import { MatchDescription } from '../MatchDescription'
import { MatchProfileCardMobile } from '../MatchProfileCardMobile'

type Props = {
  tournamentData: TournamentData,
}

export const LiveMatch = ({
  tournamentData,
}: Props) => {
  const {
    events,
    matchPlaylists,
    profile,
    selectedPlaylist,
  } = useMatchPageStore()

  const {
    chapters,
    onDurationChange,
    onPlayerProgressChange,
    onPlayingChange,
    onPlaylistSelect,
    resume,
    streamUrl,
  } = useLiveMatch()

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

      <MatchSidePlaylists
        tournamentData={tournamentData}
        events={events}
        onSelect={onPlaylistSelect}
        playlists={matchPlaylists}
        profile={profile}
        selectedPlaylist={selectedPlaylist}
      />
    </Fragment>
  )
}
