import isEmpty from 'lodash/isEmpty'

import { StreamPlayer } from 'features/StreamPlayer'
import { MultiSourcePlayer } from 'features/MultiSourcePlayer'
import { ProfileHeader } from 'features/ProfileHeader'
import { MainWrapper } from 'features/MainWrapper'
import { UserFavorites } from 'features/UserFavorites'
import { MediaQuery } from 'features/MediaQuery'

import { MatchProfileCard } from './MatchProfileCard'
import { usePlayerProgressReporter } from './hooks/usePlayerProgressReporter'
import { useMatchProfile } from './hooks/useMatchProfile'
import { useVideoData } from './hooks/useVideoData'
import { MainWrapper as Wrapper, Container } from './styled'

export const MatchPage = () => {
  const profile = useMatchProfile()
  const {
    isLastPlayPositionFetching,
    lastPlayPosition,
    url,
    videos,
  } = useVideoData()
  const { onPlayerProgressChange, onPlayingChange } = usePlayerProgressReporter()

  const isLiveMatch = Boolean(url) && !isLastPlayPositionFetching
  const isFinishedMatch = !isEmpty(videos) && !isLastPlayPositionFetching

  return (
    <MainWrapper>
      <MediaQuery minDevice='laptop'>
        <UserFavorites />
      </MediaQuery>
      <ProfileHeader />
      <Wrapper>
        <MatchProfileCard profile={profile} />
        <Container>
          {
            isLiveMatch && (
              <StreamPlayer
                url={url}
                onPlayingChange={onPlayingChange}
                onProgressChange={onPlayerProgressChange}
                resumeFrom={lastPlayPosition.second}
              />
            )
          }
          {
            isFinishedMatch && (
              <MultiSourcePlayer
                videos={videos}
                onPlayingChange={onPlayingChange}
                onProgressChange={onPlayerProgressChange}
                resumeFrom={lastPlayPosition}
              />
            )
          }
        </Container>
      </Wrapper>
    </MainWrapper>
  )
}
