import {
  useCallback,
  useEffect,
  useLayoutEffect,
  useRef,
  useState,
} from 'react'

import isEmpty from 'lodash/isEmpty'

import { MatchesSlider } from 'features/MatchesSlider'
import { TimelineTournamentList, useTimeline } from 'features/MatchesTimeline/hooks'
import { InfiniteScroll } from 'features/InfiniteScroll'
import { T9n } from 'features/T9n'
import { TournamentSubtitle } from 'features/TournamentSubtitle'

import { ProfileTypes } from 'config'

import {
  Content,
  Tournament,
  RowWrapper,
  Wrapper,
  TournamentLogo,
  Loading,
  TournamentSubtitleWrapper,
} from './styled'

const TOURNAMENT_LIMIT = 10
const MATCH_COUNT = 6
const PADDING = 30
const GAP_COUNT = 5
const SLIDER_ITEM_GAP = 0.9 // rem

export const MatchesTimeline = () => {
  const {
    isTimelineFetching,
    onlineUpcomingMatches,
    tournamentList,
  } = useTimeline()

  const [tournaments, setTournaments] = useState<TimelineTournamentList>([])

  const pageRef = useRef(0)
  const isLastPageRef = useRef(false)
  const wrapperRef = useRef<HTMLDivElement>(null)

  const [cardSize, setCardSize] = useState(0)

  // вычисляем размеры плитки
  useLayoutEffect(() => {
    const offsetWidth = wrapperRef.current?.offsetWidth
    const ulItemGapFromRem = SLIDER_ITEM_GAP * parseFloat(
      getComputedStyle(document.documentElement).fontSize,
    )

    if (offsetWidth) {
      const size = Math.round(
        ((offsetWidth - (ulItemGapFromRem * GAP_COUNT) - PADDING) / MATCH_COUNT),
      )

      setCardSize(size)
    }
  }, [])

  const getTournaments = useCallback(() => tournamentList.slice(
    pageRef.current * TOURNAMENT_LIMIT,
    pageRef.current * TOURNAMENT_LIMIT + TOURNAMENT_LIMIT,
  ), [tournamentList])

  const getMoreTournaments = () => {
    if (isLastPageRef.current) return
    const res = getTournaments()

    if (res.length) {
      setTournaments((prev) => ([
        ...prev,
        ...res,
      ]))
      pageRef.current++
    } else {
      isLastPageRef.current = true
    }
  }

  useEffect(() => {
    if (tournamentList.length) {
      pageRef.current = 0
      isLastPageRef.current = false
      tournamentList.length > 0 && setTournaments(getTournaments())
      pageRef.current = 1
    }
  }, [getTournaments, tournamentList])

  return (
    <InfiniteScroll fullPageScroll onFetchMore={getMoreTournaments}>
      <Wrapper ref={wrapperRef}>
        {isTimelineFetching && <Loading><T9n t='loading' />...</Loading>}
        {(!isEmpty(onlineUpcomingMatches)) && (
          <RowWrapper>
            <Content>
              <Tournament
                size={cardSize}
                isOnlineUpcoming
              >
                LIVE & UPCOMING
              </Tournament>
              <MatchesSlider
                cardSize={cardSize}
                matches={onlineUpcomingMatches}
              />
            </Content>
          </RowWrapper>
        )}
        {tournaments.map(({
          matches,
          sport_id,
          tournament,
          tournament_id,
        }) => (
          <RowWrapper key={`${tournament_id}_${sport_id}`}>
            <TournamentSubtitleWrapper>
              <TournamentSubtitle
                sportInfo={matches[0].sportInfo}
                countryId={matches[0].countryId}
                sportType={sport_id}
                tournament={tournament}
              />
            </TournamentSubtitleWrapper>
            <Content>
              <Tournament
                size={cardSize}
                gradientColor={tournament.color}
              >
                <TournamentLogo
                  id={tournament_id}
                  profileType={ProfileTypes.TOURNAMENTS}
                  sportType={sport_id}
                />
              </Tournament>
              <MatchesSlider
                cardSize={cardSize}
                matches={matches}
              />
            </Content>
          </RowWrapper>
        ))}
      </Wrapper>
    </InfiniteScroll>
  )
}
