import type { KeyboardEvent } from 'react'
import { useCallback } from 'react'
import { useHistory } from 'react-router-dom'

import includes from 'lodash/includes'

import { PAGES, ProfileTypes } from 'config'

import type { Match } from 'features/Matches'
import { useMatchPopupStore } from 'features/MatchPopup'
import { useBuyMatchPopupStore } from 'features/BuyMatchPopup'
import { useAuthStore } from 'features/AuthStore'
import { getProfileUrl } from 'features/ProfileLink/helpers'
import { MatchAccess } from 'features/Matches/helpers/getMatchClickAction'
import { checkPage } from 'helpers/checkPage'

export const useCard = (match: Match) => {
  const { openMatchPopup } = useMatchPopupStore()
  const { open: openBuyMatchPopup } = useBuyMatchPopupStore()
  const history = useHistory()
  const { user } = useAuthStore()
  const redirectToMatchPage = useCallback(() => {
    const matchLink = getProfileUrl({
      id: match.id,
      profileType: ProfileTypes.MATCHES,
      sportType: match.sportType,
    })
    return history.push(matchLink)
  }, [
    history,
    match.id,
    match.sportType,
  ])

  const onMatchClick = useCallback(() => {
    switch (match.access) {
      case MatchAccess.ViewMatchPopupWithoutUser:
        redirectToMatchPage()
        break
      case MatchAccess.CanBuyMatch:
        openBuyMatchPopup(match)
        break
      case MatchAccess.ViewMatchPopup:
        openMatchPopup(match)
        break
      case MatchAccess.RedirectToProfile:
        redirectToMatchPage()
        break
      case MatchAccess.NoCountryAccess:
      case MatchAccess.NoAccess:
      default:
        break
    }
  }, [
    match,
    openMatchPopup,
    openBuyMatchPopup,
    redirectToMatchPage,
  ])

  const onKeyPress = useCallback((e: KeyboardEvent<HTMLLIElement>) => {
    if (e.key === 'Enter') {
      onMatchClick()
    }
  }, [onMatchClick])

  const isNeedFormatTimeChanged = includes(['US', 'CA'], user?.profile.country_code)

  const isPlayerPage = checkPage(PAGES.player)
  const isTeamPage = checkPage(PAGES.team)
  const isTournamentPage = checkPage(PAGES.tournament)

  const isOwnedMatches = isPlayerPage || isTeamPage || isTournamentPage

  return {
    isNeedFormatTimeChanged,
    isOwnedMatches,
    onKeyPress,
    onMatchClick,
  }
}
