import { useMemo } from 'react'

import orderBy from 'lodash/orderBy'

import { ProfileTypes } from 'config'
import { TournamentListProps } from 'features/TournamentList'
import type { Match } from 'features/Matches'
import { useHeaderFiltersStore } from 'features/HeaderFilters'
import { useUserFavoritesStore } from 'features/UserFavorites/store'

interface TournamentsSortProps {
  id: number,
  isFavorite: boolean,
  isLive: boolean,
  isSuperTournament: boolean,
  sportType: number,
}

export const useTournaments = (matches: Array<Match>) => {
  const {
    compareSport,
    selectedLeague,
    selectedSport,
  } = useHeaderFiltersStore()
  const { isInFavorites } = useUserFavoritesStore()

  const compareLeague = (id: number| string) => {
    if (selectedLeague[0] === 'all_competitions') {
      return true
    }
    return (selectedLeague.indexOf(id) >= 0)
  }

  // eslint-disable-next-line react-hooks/exhaustive-deps
  const tournamentSort: Array<TournamentsSortProps> = []

  const tournaments = matches.reduce((acc: TournamentListProps, match: Match) => {
    if (matches.length === 0) return {}

    const uniqTournamentId = `${match.sportType}_${match.tournament.id}`

    const tournamentInFavorites = isInFavorites(
      ProfileTypes.TOURNAMENTS,
      // в избранном могут быть только обычные турниры
      match.tournament.is_super_tournament ? match.group.id : match.tournament.id,
    )

    if (!acc[`${match.sportType}_${match.tournament.id}`] && compareSport(match, selectedSport)
      && compareLeague(uniqTournamentId)) {
      const tournament = {
        ...match.tournament,
        countryId: match.countryId,
        isFavorite: tournamentInFavorites,
        live: match.live,
        matches: [match],
        sportType: match.sportType,
      }
      acc[uniqTournamentId] = {
        tournament: {
          ...tournament,
        },
        tournamentMatches: [match],
      }
      tournamentSort.push({
        id: match.tournament.id,
        isFavorite: tournamentInFavorites,
        isLive: match.live,
        isSuperTournament: Boolean(match.tournament.is_super_tournament),
        sportType: match.sportType,
      })
    } else if (compareSport(match, selectedSport) && compareLeague(uniqTournamentId)) {
      acc[uniqTournamentId] = {
        ...acc[uniqTournamentId],
        tournament: {
          ...acc[uniqTournamentId].tournament,
          live: acc[uniqTournamentId]?.tournament.live
            ? acc[uniqTournamentId]?.tournament.live
            : match.live,
        },
        tournamentMatches: [...acc[uniqTournamentId].tournamentMatches, match],
      }
    }
    return acc
  }, {})

  const tournamentsSorted = useMemo(() => orderBy(
    tournamentSort,
    ['isLive', 'isFavorite', 'isSuperTournament'],
    ['desc', 'desc', 'desc'],
  ), [tournamentSort])

  return {
    compareSport,
    tournamentSort: tournamentsSorted,
    tournaments,
  }
}
