import {
  useEffect,
  useState,
  useCallback,
} from 'react'
import { useHistory } from 'react-router'

import type { TournamentInfo } from 'requests'
import {
  getTournamentInfo,
  getTournamentMatches,
} from 'requests'

import { openSubscribePopup, redirectToUrl } from 'helpers'

import { PAGES } from 'config/pages'

import { useName } from 'features/Name'

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

import { usePageParams } from 'hooks/usePageParams'

import { isPermittedTournament } from '../../helpers/isPermittedTournament'
import { getLandingStatus } from '../../requests/getLandingStatus'
import { useProfileCard } from '../ProfileCard/hooks'
import { useBuyMatchPopupStore } from '../BuyMatchPopup'
import { MATCH_CONFIG } from '../BuyMatchPopup/store/hooks/useSubscriptions'
import { useAuthStore } from '../AuthStore'

export const useTournamentPage = () => {
  const [tournamentProfile, setTournamentProfile] = useState<TournamentInfo>(null)
  const { profileId: tournamentId, sportType } = usePageParams()
  const { open: openBuyMatchPopup } = useBuyMatchPopupStore()
  const country = useName(tournamentProfile?.country || {})
  const history = useHistory()

  const {
    isFromLanding,
    setIsFromLanding,
    setLandingUrlFrom,
    user,
  } = useAuthStore()

  const { isFavorite, toggleFavorites } = useProfileCard()

  useEffect(
    () => {
      if (!isPermittedTournament(tournamentId, sportType)) {
        history.push('/')
      }
      getTournamentInfo(sportType, tournamentId)
        .then(setTournamentProfile)
    },
    [
      history,
      sportType,
      tournamentId,
    ],
  )

  useEffect(() => {
    if (user || isFromLanding || history.length > 1) return
    setLandingUrlFrom(window.location.pathname)
    getLandingStatus({ sportType, tournamentId })
      .then((data) => {
        sessionStorage.setItem(
          'landingData',
          JSON.stringify({ ...data, defaultLanding: false }),
        )
        setIsFromLanding(false)
        if (data.landing_id) redirectToUrl(`${PAGES.landing}/${data.landing_id}`)
      })
      .catch(() => {
        sessionStorage.setItem('landingData', JSON.stringify({
          defaultLanding: true,
          sportType,
          tournamentId,
        }))
        redirectToUrl(`${PAGES.landing}/default`)
      })
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [
    setLandingUrlFrom,
    isFromLanding,
    tournamentId,
    setIsFromLanding,
    sportType,
    user,
  ])

  useEffect(() => {
    !isFavorite
    && checkUrlParams('from') === 'landing'
    && toggleFavorites()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  const fetchMatches = useCallback(
    (limit: number, offset: number) => getTournamentMatches({
      limit,
      offset,
      sportType,
      tournamentId,
    }),
    [
      tournamentId,
      sportType,
    ],
  )

  const profile = tournamentProfile && {
    additionalInfo: tournamentProfile.country,
    name_eng: tournamentProfile.name_eng,
    name_rus: tournamentProfile.name_rus,
  }

  useEffect(() => {
    openSubscribePopup(
      {
        matchConfig: MATCH_CONFIG,
        openBuyMatchPopup,
      },
    )
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  return {
    fetchMatches,
    headerImage: tournamentProfile?.header_image,
    infoItems: [country],
    profile,
    tournamentId,
    user,
  }
}
