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

import { PAGES } from 'config/pages'

import { MatchCard } from 'features/MatchCard'
import { TournamentList } from 'features/TournamentList'
import type { Match } from 'features/Matches'
import { useHeaderFiltersStore } from 'features/HeaderFilters'

import { Wrapper } from './styled'

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

export const MatchesGrid = memo(({ matches }: MatchesGridProps) => {
  const isHomePage = useRouteMatch(PAGES.home)?.isExact

  const {
    isShowTournament,
    selectedFilters,
    selectedLeague,
  } = useHeaderFiltersStore()

  const filteredMatches = () => {
    if (isHomePage && selectedFilters.length && isShowTournament) {
      return matches.filter(
        (match) => (match.live && selectedFilters.indexOf('live') >= 0)
            || (selectedFilters.indexOf('upcoming') >= 0
            && match.date > new Date())
            || (selectedFilters.indexOf('completed') >= 0 && match.is_finished),
      )
    }
    if (isHomePage && selectedLeague.length && !isShowTournament) {
      return matches.filter((match) => ((selectedLeague.indexOf(match.tournament.id) >= 0
      || selectedLeague[0] === 'all_competitions')))
    }
    return matches
  }

  return (
    <Wrapper>
      {isHomePage && isShowTournament ? (
        <TournamentList matches={filteredMatches()} />
      ) : (
        filteredMatches().map((match) => <MatchCard key={match.id} match={match} />)
      )}
    </Wrapper>
  )
})
