import { useEffect } from 'react'
import { useHistory } from 'react-router'

import { ProfileHeader } from 'features/ProfileHeader'
import { UserFavorites } from 'features/UserFavorites'
import { useUserFavoritesStore } from 'features/UserFavorites/store'
import {
  PageWrapper,
  Main,
} from 'features/PageLayout'

import { FavoritesActions } from 'requests'

import { ProfileTypes } from 'config'
import { client } from 'config/clients'
import { isIOS } from 'config/userAgent'

import { usePageLogger } from 'hooks/usePageLogger'
import { usePageParams } from 'hooks/usePageParams'

import { checkUrlParams } from 'helpers/parseUrlParams/parseUrlParams'
import { MatchPageStore, useMatchPageStore } from './store'
import { SubscriptionGuard } from './components/SubscriptionGuard'
import { LiveMatch } from './components/LiveMatch'
import { Wrapper } from './styled'
import { FinishedMatch } from './components/FinishedMatch'
import { FavouriteTeamPopup } from './components/FavouriteTeam'

const MatchPageComponent = () => {
  usePageLogger()
  const history = useHistory()
  const { addRemoveFavorite, userFavorites } = useUserFavoritesStore()

  const {
    isStarted,
    profile,
    user,
  } = useMatchPageStore()
  const isFavorite = profile && userFavorites?.find((fav) => fav.id === profile?.tournament.id)

  const {
    profileType,
    sportType,
  } = usePageParams()

  useEffect(() => {
    let timer = 0
    timer = window.setTimeout(() => {
      if (profile && !isFavorite) {
        addRemoveFavorite({
          action: FavoritesActions.ADD,
          id: profile?.tournament.id,
          isAuto: true,
          sport: sportType,
          type: ProfileTypes.TOURNAMENTS,
        })
      }
    }, 60000)

    return () => {
      clearTimeout(timer)
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [profile, profileType])
  useEffect(() => {
    if (
      profile
        && !isFavorite
        && checkUrlParams('from') === 'landing') {
      addRemoveFavorite({
        action: FavoritesActions.ADD,
        id: profile?.tournament.id,
        isAuto: true,
        sport: sportType,
        type: ProfileTypes.TOURNAMENTS,
      })
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [profile])

  const playFromScout = profile?.has_video && !profile?.live && !profile.has_hls
  const playFromOTT = (!profile?.has_video && (profile?.live || profile?.storage))
      || profile?.has_hls
  // TODO Добавить попап 'Данный матч ещё не начался'
  if (!isStarted && profile?.live === false) {
    const sportName = history.location.pathname.split('/')[1]
    history.push(`/${sportName}/tournaments/${profile.tournament.id}`)
  }

  return (
    <PageWrapper isIOS={isIOS}>
      <ProfileHeader color='#2B2A28' height={client.name === 'facr' ? 5 : 4.5} />
      <Main>
        <UserFavorites />
        <SubscriptionGuard>
          <Wrapper>
            {playFromOTT && (
              <LiveMatch />
            )}
            {playFromScout && (
              <FinishedMatch />
            )}
          </Wrapper>
        </SubscriptionGuard>
      </Main>
      {
        user && (profile?.tournament.id === 131 || profile?.tournament.id === 2032)
          && <FavouriteTeamPopup />
      }
    </PageWrapper>
  )
}

const MatchPage = () => (
  <MatchPageStore>
    <MatchPageComponent />
  </MatchPageStore>
)

export default MatchPage
