import { Loader } from 'features/Loader'
import {
  PlayerWrapper,
  CenterControls,
  PlayStop,
  LoaderWrapper,
  Backward,
  Forward,
  ControlsGradient,
  TeamsDetailsWrapper,
} from 'features/StreamPlayer/styled'
import { VideoPlayer } from 'features/VideoPlayer'
import { Controls } from 'features/StreamPlayer/components/Controls'
import { Name } from 'features/Name'
import RewindMobile from 'features/StreamPlayer/components/RewindMobile'
import { FiltersPopup } from 'features/MatchSidePlaylists/components/FiltersPopup'
import { useAuthStore } from 'features/AuthStore'

import { isMobileDevice } from 'config/userAgent'

import { AccessTimer } from 'components/AccessTimer'

import type { Props } from './hooks'
import { useMultiSourcePlayer } from './hooks'
import { Players } from './types'
import { REWIND_SECONDS } from './config'

export const MultiSourcePlayer = (props: Props) => {
  const {
    access,
    isOpenPopup,
    profile,
  } = props

  const {
    activeChapterIndex,
    activePlayer,
    activeSrc,
    allPlayedProgress,
    centerControlsVisible,
    chapters,
    duration,
    hideCenterControls,
    isFirstChapterPlaying,
    isFullscreen,
    isLastChapterPlaying,
    loadedProgress,
    mainControlsVisible,
    muted,
    nextSrc,
    numberOfChapters,
    onEnded,
    onError,
    onFullscreenClick,
    onLoadedProgress,
    onMouseEnter,
    onMouseLeave,
    onMouseMove,
    onPause,
    onPlayedProgress,
    onPlayerClick,
    onProgressChange,
    onQualitySelect,
    onReady,
    onTouchEnd,
    onTouchStart,
    onVolumeChange,
    onVolumeClick,
    playedProgress,
    playing,
    playNextChapter,
    playPrevChapter,
    ready,
    rewindBackward,
    rewindForward,
    seek,
    selectedQuality,
    showCenterControls,
    togglePlaying,
    video1Ref,
    video2Ref,
    videoQualities,
    volume,
    volumeInPercent,
    wrapperRef,
  } = useMultiSourcePlayer(props)
  const firstPlayerActive = activePlayer === Players.PLAYER1
  const currentVideo = firstPlayerActive ? video1Ref : video2Ref
  const { user } = useAuthStore()

  return (
    <PlayerWrapper
      ref={wrapperRef}
      playing={playing}
      onClick={isMobileDevice ? showCenterControls : onPlayerClick}
      onMouseMove={onMouseMove}
      onMouseEnter={onMouseEnter}
      onMouseLeave={onMouseLeave}
      onTouchStart={onTouchStart}
      onTouchEnd={onTouchEnd}
    >
      {
        !ready && (
          <LoaderWrapper buffering>
            <Loader color='#515151' />
          </LoaderWrapper>
        )
      }
      {isOpenPopup && <FiltersPopup />}
      <VideoPlayer
        src={firstPlayerActive ? activeSrc : nextSrc}
        playing={firstPlayerActive ? playing : false}
        hidden={!firstPlayerActive}
        muted={muted}
        volume={volume}
        ref={video1Ref}
        seek={seek[Players.PLAYER1]}
        isFullscreen={isFullscreen}
        onLoadedProgress={firstPlayerActive ? onLoadedProgress : undefined}
        onPlayedProgress={firstPlayerActive ? onPlayedProgress : undefined}
        onEnded={onEnded}
        onPause={firstPlayerActive ? onPause : undefined}
        onError={onError}
        onReady={onReady}
      />
      <VideoPlayer
        src={!firstPlayerActive ? activeSrc : nextSrc}
        playing={!firstPlayerActive ? playing : false}
        hidden={firstPlayerActive}
        muted={muted}
        volume={volume}
        ref={video2Ref}
        seek={seek[Players.PLAYER2]}
        isFullscreen={isFullscreen}
        onLoadedProgress={!firstPlayerActive ? onLoadedProgress : undefined}
        onPlayedProgress={!firstPlayerActive ? onPlayedProgress : undefined}
        onEnded={onEnded}
        onPause={!firstPlayerActive ? onPause : undefined}
        onError={onError}
        onReady={onReady}
      />

      {isMobileDevice && isFullscreen && mainControlsVisible && profile && (
        <TeamsDetailsWrapper>
          <Name nameObj={profile.team1} />
          {` ${profile.team1.score}-${profile.team2.score} `}
          <Name nameObj={profile.team2} />
        </TeamsDetailsWrapper>
      )}

      {ready && (
        <CenterControls
          controlsVisible={centerControlsVisible}
          playing={!currentVideo.current?.paused}
        >
          {isMobileDevice && playing ? (
            <RewindMobile isBackward rewindCallback={rewindBackward} />
          ) : (
            <Backward
              size={isMobileDevice ? 'sm' : 'lg'}
              onClick={rewindBackward}
            >
              {REWIND_SECONDS}
            </Backward>
          )}
          <PlayStop
            size='lg'
            marginRight={0}
            playing={playing}
            onClickCapture={() => {
              togglePlaying()
              hideCenterControls()
            }}
          />
          {isMobileDevice && playing
            ? <RewindMobile isForward rewindCallback={rewindForward} />
            : (
              <Forward
                size={isMobileDevice ? 'sm' : 'lg'}
                onClick={rewindForward}
              >
                {REWIND_SECONDS}
              </Forward>
            )}
        </CenterControls>
      )}
      <Controls
        activeChapterIndex={activeChapterIndex}
        activePlayer={activePlayer}
        allPlayedProgress={allPlayedProgress}
        multiSourceChapters={chapters}
        controlsVisible={mainControlsVisible}
        duration={duration}
        isFirstChapterPlaying={isFirstChapterPlaying}
        isFullscreen={isFullscreen}
        isLastChapterPlaying={isLastChapterPlaying}
        loadedProgress={loadedProgress}
        muted={muted}
        numberOfChapters={numberOfChapters}
        onFullscreenClick={onFullscreenClick}
        onProgressChange={onProgressChange}
        onQualitySelect={onQualitySelect}
        onTouchEnd={onTouchEnd}
        onTouchStart={onTouchStart}
        onVolumeChange={onVolumeChange}
        onVolumeClick={onVolumeClick}
        playNextChapter={playNextChapter}
        playPrevChapter={playPrevChapter}
        playedProgress={playedProgress}
        playing={playing}
        rewindBackward={rewindBackward}
        rewindForward={rewindForward}
        selectedQuality={selectedQuality}
        src={firstPlayerActive ? activeSrc : nextSrc}
        togglePlaying={togglePlaying}
        videoQualities={videoQualities}
        videoRef={currentVideo}
        volume={volume}
        volumeInPercent={volumeInPercent}
      />
      <ControlsGradient isVisible={mainControlsVisible} />
      {!user && (
        <AccessTimer
          access={access}
          isFullscreen={isFullscreen}
          onFullscreenClick={onFullscreenClick}
          playing={ready && playing && !!playedProgress}
          videoRef={currentVideo}
        />
      )}
    </PlayerWrapper>
  )
}
