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

import { WaterMark } from 'components/WaterMark'
import { AccessTimer } from 'components/AccessTimer'

import { isMobileDevice } from 'config/userAgent'

import { REWIND_SECONDS } from './config'

import {
  PlayerWrapper,
  CenterControls,
  PlayStop,
  LoaderWrapper,
  Backward,
  Forward,
  ControlsGradient,
  TeamsDetailsWrapper,
} from './styled'
import type { Props } from './hooks'
import { useVideoPlayer } from './hooks'
import { useAuthStore } from '../AuthStore'
import { Controls } from './components/Controls'
import RewindMobile from './components/RewindMobile'

const tournamentsWithWatermark = {
  316: 'Tunisia',
  1136: 'Brasil',
}
/**
 * HLS плеер, применяется на лайв и завершенных матчах
 */
export const StreamPlayer = (props: Props) => {
  const {
    access,
    isOpenFiltersPopup,
    profile,
  } = useMatchPageStore()
  const { user } = useAuthStore()

  const {
    activeChapterIndex,
    allPlayedProgress,
    audioTracks,
    backToLive,
    buffering,
    centerControlsVisible,
    changeAudioTrack,
    chapters,
    duration,
    hideCenterControls,
    isFullscreen,
    isLive,
    loadedProgress,
    mainControlsVisible,
    muted,
    onDuration,
    onError,
    onFullscreenClick,
    onLoadedProgress,
    onMouseEnter,
    onMouseLeave,
    onMouseMove,
    onPause,
    onPlay,
    onPlayedProgress,
    onPlayerClick,
    onPlaying,
    onProgressChange,
    onQualitySelect,
    onReady,
    onTouchEnd,
    onTouchStart,
    onVolumeChange,
    onVolumeClick,
    onWaiting,
    playedProgress,
    playing,
    ready,
    rewindBackward,
    rewindForward,
    seek,
    selectedAudioTrack,
    selectedQuality,
    showCenterControls,
    togglePlaying,
    url,
    videoQualities,
    videoRef,
    volume,
    volumeInPercent,
    wrapperRef,
  } = useVideoPlayer(props)

  return (
    <PlayerWrapper
      ref={wrapperRef}
      playing={playing}
      onClick={isMobileDevice ? showCenterControls : onPlayerClick}
      onMouseMove={onMouseMove}
      onMouseEnter={onMouseEnter}
      onMouseLeave={onMouseLeave}
      onTouchStart={onTouchStart}
      onTouchEnd={onTouchEnd}
    >
      {isOpenFiltersPopup && <FiltersPopup />}
      <LoaderWrapper buffering={buffering}>
        <Loader color='#515151' />
      </LoaderWrapper>
      {user
        && Boolean(
          tournamentsWithWatermark[profile?.tournament.id as keyof typeof tournamentsWithWatermark],
        )
        && playing
        && isLive
        && (
          <WaterMark value={user?.profile?.sub} />
        )}
      <VideoPlayer
        width='100%'
        height='100%'
        src={url}
        ref={videoRef}
        playing={playing}
        volume={volume}
        muted={muted}
        seek={seek}
        isFullscreen={isFullscreen}
        onLoadedProgress={onLoadedProgress}
        onPlayedProgress={onPlayedProgress}
        onDurationChange={onDuration}
        onEnded={togglePlaying}
        onReady={onReady}
        onPause={onPause}
        onPlay={onPlay}
        onPlaying={onPlaying}
        onWaiting={onWaiting}
        onError={onError}
        crossOrigin='use-credentials'
      />

      {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={playing}>
          {isMobileDevice
            ? <RewindMobile isBackward rewindCallback={rewindBackward} />
            : <Backward size='lg' onClick={rewindBackward}>{REWIND_SECONDS}</Backward>}
          <PlayStop
            size='lg'
            fullWidth
            marginRight={0}
            playing={playing}
            onClickCapture={() => {
              togglePlaying()
              hideCenterControls()
            }}
          />
          {isMobileDevice
            ? <RewindMobile isForward rewindCallback={rewindForward} />
            : <Forward size='lg' onClick={rewindForward}>{REWIND_SECONDS}</Forward>}
        </CenterControls>
      )}

      <Controls
        allPlayedProgress={allPlayedProgress}
        audioTracks={audioTracks}
        backToLive={backToLive}
        changeAudioTrack={changeAudioTrack}
        controlsVisible={mainControlsVisible}
        duration={duration}
        isFullscreen={isFullscreen}
        isLive={profile?.live}
        isStorage={profile?.storage}
        loadedProgress={loadedProgress}
        muted={muted}
        onFullscreenClick={onFullscreenClick}
        onProgressChange={onProgressChange}
        onQualitySelect={onQualitySelect}
        onTouchEnd={onTouchEnd}
        onTouchStart={onTouchStart}
        onVolumeChange={onVolumeChange}
        onVolumeClick={onVolumeClick}
        playedProgress={playedProgress}
        playing={playing}
        rewindBackward={rewindBackward}
        rewindForward={rewindForward}
        selectedQuality={selectedQuality}
        togglePlaying={togglePlaying}
        videoQualities={videoQualities}
        videoRef={videoRef}
        volume={volume}
        volumeInPercent={volumeInPercent}
        activeChapterIndex={activeChapterIndex}
        liveChapters={chapters}
        selectedAudioTrack={selectedAudioTrack}
      />
      <ControlsGradient isVisible={mainControlsVisible} />
      {!user && (
        <AccessTimer
          access={access}
          isFullscreen={isFullscreen}
          onFullscreenClick={onFullscreenClick}
          playing={ready && playing && !!playedProgress}
          videoRef={videoRef}
        />
      )}
    </PlayerWrapper>
  )
}
