import {
  Fragment,
  useMemo,
  memo,
} from 'react'

import { T9n } from 'features/T9n'
import { InfiniteScroll } from 'features/InfiniteScroll'
import { Loader } from 'features/Loader'
import { isMobileDevice } from 'config/userAgent'

import type { Props } from './hooks'
import { useMatches } from './hooks'
import { MatchesList } from './components/MatchesList'
import { Loading } from './styled'

export type { Match } from './hooks'

export const Matches = memo((props: Props) => {
  const {
    fetchMoreMatches,
    isFetching,
    matches: {
      broadcast,
      features,
      highlights,
      isVideoSections,
    },
  } = useMatches(props)

  const mobileView = useMemo(() => (
    isFetching ? (
      <Loader color='white' />
    ) : (
      <MatchesList
        as='grid'
        matches={broadcast}
      />
    )
  ), [isFetching, broadcast])

  const desktopView = useMemo(() => (
    <>
      <MatchesList
        as='grid'
        matches={broadcast}
      />
      {isFetching && <Loading><T9n t='loading' />...</Loading>}
    </>
  ), [isFetching, broadcast])

  if (isVideoSections) {
    return (
      <Fragment>
        <MatchesList
          as='slider'
          title='broadcast'
          matches={broadcast}
        />
        <MatchesList
          as='slider'
          title='round_highilights'
          matches={highlights}
        />
        <MatchesList
          as='slider'
          title='features'
          matches={features}
        />
      </Fragment>
    )
  }

  return (
    <InfiniteScroll fullPageScroll onFetchMore={fetchMoreMatches}>
      {isMobileDevice ? mobileView : desktopView}
    </InfiniteScroll>
  )
})
