import { useRouteMatch } from 'react-router-dom'

import type { Match } from 'features/Matches'
import { MatchCard } from 'features/MatchCard'

import type { TournamentType } from 'requests/getMatches/types'

import { PAGES } from 'config/pages'
import { isMobileDevice } from 'config/userAgent'

import { TournamentMobile } from './components/TournamentMobile'
import { useTournaments } from './hooks'
import { CollapseTournament } from './components/CollapseTournament'

type TournamentTypeProps = {
  matches: Array<Match>,
}

export type TournamentProps = {
  tournament: TournamentType & {
    countryId: number,
    isFavorite: boolean,
    live: boolean,
    sportType: number,
  },
  tournamentMatches: Array<Match>,
}

export type TournamentListProps = {
  [key: string]: TournamentProps,
}

export const TournamentList = ({ matches }: TournamentTypeProps) => {
  const { tournaments, tournamentSort } = useTournaments(matches)
  const isHomePage = useRouteMatch(PAGES.home)?.isExact

  switch (true) {
    case isMobileDevice && isHomePage:
      return (
        <>
          {tournamentSort?.map(({ id, sportType }) => (
            <TournamentMobile
              key={`${sportType}_${id}`}
              tournament={tournaments[`${sportType}_${id}`].tournament}
              tournamentMatches={tournaments[`${sportType}_${id}`].tournamentMatches}
            />
          ))}
        </>
      )
    case isHomePage && matches.length >= 12:
      return (
        <>
          {tournamentSort?.map(({ id, sportType }) => (
            <CollapseTournament
              key={`${sportType}_${id}`}
              tournament={tournaments[`${sportType}_${id}`].tournament}
              tournamentMatches={tournaments[`${sportType}_${id}`].tournamentMatches}
            />
          ))}
        </>
      )
    default:
      return (
        <>
          {matches.map((match) => (
            <MatchCard key={match.id} match={match} />
          ))}
        </>
      )
  }
}
