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

import { useTour } from '@reactour/tour'

import { useTheme } from 'styled-components'

import find from 'lodash/find'

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

import { FavoritesActions } from 'requests'

import {
  ProfileTypes,
  isIOS,
  client,
  isMobileDevice,
} from 'config'

import {
  useScreenOrientation,
  usePageLogger,
  usePageParams,
} from 'hooks'

import { checkUrlParams } from 'helpers/parseUrlParams/parseUrlParams'

import { TourProvider } from 'features/MatchTour'

import { MatchPageStore, useMatchPageStore } from './store'
import { SubscriptionGuard } from './components/SubscriptionGuard'
import { LiveMatch } from './components/LiveMatch'
import { FavouriteTeamPopup } from './components/FavouriteTeam'
import { PLAYER_MOBILE_FULL_SCREEN } from '../../components/Ads/types'
import { MobileAd } from '../../components/Ads/components/MobileAd'

import { Wrapper } from './styled'

const MatchPageComponent = () => {
  usePageLogger()
  const history = useHistory()
  const orientation = useScreenOrientation()
  const { addRemoveFavorite, userFavorites } = useUserFavoritesStore()
  const { colors } = useTheme()

  const {
    ads,
    isStarted,
    profile,
    user,
  } = useMatchPageStore()

  const isFavorite = profile && userFavorites?.find((fav) => fav.id === profile?.tournament.id)

  const {
    profileType,
    sportType,
  } = usePageParams()

  const { isOpen } = useTour()

  const {
    HORIZONTAL_FULL_SCREEN,
    VERTICAL_FULL_SCREEN,
  } = PLAYER_MOBILE_FULL_SCREEN

  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])

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

  const currentOrientation = orientation === 0
    ? VERTICAL_FULL_SCREEN
    : HORIZONTAL_FULL_SCREEN

  const currentAds = useMemo(
    () => (find(ads, (ad) => ad.position.id === currentOrientation)),
    [ads, currentOrientation],
  )

  return (
    <PageWrapper
      isIOS={isIOS}
      isTourOpen={Boolean(isOpen)}
    >
      {isMobileDevice
        && currentAds
        && <MobileAd ad={currentAds} />}
      <ProfileHeader color={colors.matchHeaderBackground} height={client.name === 'facr' ? 5 : 4.5} />
      <Main>
        <UserFavorites />
        <SubscriptionGuard>
          <Wrapper isTourOpen={Boolean(isOpen)}>
            <LiveMatch />
          </Wrapper>
        </SubscriptionGuard>
      </Main>
      {
        user
          && profile?.sub
          && (profile?.tournament.id === 131 || profile?.tournament.id === 2032)
          && <FavouriteTeamPopup />
      }
    </PageWrapper>
  )
}

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

export default MatchPage
