import { Fragment, useState } from 'react'

import isEmpty from 'lodash/isEmpty'

import type { TCircleAnimation } from 'features/CircleAnimationBar'
import { initialCircleAnimation } from 'features/CircleAnimationBar'
import { MatchSidePlaylists } from 'features/MatchSidePlaylists'
import { MultiSourcePlayer } from 'features/MultiSourcePlayer'

import { SettingsPopup } from '../SettingsPopup'

import { useFinishedMatch } from './hooks'
import { Container } from '../../styled'
import { Modal } from './styled'
import { MatchDescription } from '../MatchDescription'
import { useMatchPageStore } from '../../store'

export const FinishedMatch = () => {
  const [circleAnimation, setCircleAnimation] = useState<TCircleAnimation>(initialCircleAnimation)
  const {
    isOpenPopup,
    profile,
    setPlayingProgress,
  } = useMatchPageStore()
  const {
    chapters,
    closeSettingsPopup,
    isSettingsPopupOpen,
    onPlayingChange,
    onPlaylistSelect,
    selectedPlaylist,
    setEpisodesSettings,
  } = useFinishedMatch()

  return (
    <Fragment>
      <Modal
        close={closeSettingsPopup}
        isOpen={isSettingsPopupOpen}
        withCloseButton={false}
      >
        <SettingsPopup
          onWatchEpisodesClick={setEpisodesSettings}
          closePopup={closeSettingsPopup}
          profile={profile}
          selectedPlaylist={selectedPlaylist}
        />
      </Modal>

      <Container>
        {!isEmpty(chapters) && (
          <Fragment>
            <MultiSourcePlayer
              setCircleAnimation={setCircleAnimation}
              isOpenPopup={isOpenPopup}
              chapters={chapters}
              onPlayingChange={onPlayingChange}
              onPlayerProgressChange={setPlayingProgress}
              profile={profile}
            />
            <MatchDescription />
          </Fragment>
        )}
      </Container>

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