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: number]: 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 }) => (
            <TournamentMobile
              key={id}
              tournament={tournaments[id].tournament}
              tournamentMatches={tournaments[id].tournamentMatches}
            />
          ))}
        </>
      )
    case isHomePage && matches.length >= 12:
      return (
        <>
          {tournamentSort?.map(({ id }) => (
            <CollapseTournament
              key={id}
              tournament={tournaments[id].tournament}
              tournamentMatches={tournaments[id].tournamentMatches}
            />
          ))}
        </>
      )
    default:
      return (
        <>
          {matches.map((match) => (
            <MatchCard key={match.id} match={match} />
          ))}
        </>
      )
  }
}
