import {
  Fragment,
  useMemo,
  useState,
  useRef,
  useEffect,
} from 'react'

import { format } from 'date-fns'
import map from 'lodash/map'
import sortBy from 'lodash/sortBy'
import isEmpty from 'lodash/isEmpty'

import { MatchCard } from 'features/MatchCard'
import { TournamentData } from 'features/MatchPage/types'

import { MatchInfo } from 'requests'

import { parseDate } from 'helpers/parseDate'

import { usePageParams } from 'hooks/usePageParams'

import { MatchesWrapper, Title } from './styled'

type Props = {
  additionalScrollHeight: number,
  profile: MatchInfo,
  tournamentData: TournamentData,
}

const formatDate = (date: Date) => format(date, 'yyyy-MM-dd')

export const Matches = ({
  additionalScrollHeight,
  profile,
  tournamentData,
}: Props) => {
  const { profileId } = usePageParams()

  const profileDate = useMemo(() => (
    formatDate(parseDate(profile?.date!))
  ), [profile?.date])

  const matches = useMemo(() => (
    tournamentData.matches.filter((match) => (
      formatDate(match.date) === profileDate && match.id !== profileId
    ))
  ), [profileDate, profileId, tournamentData.matches])

  const ref = useRef<HTMLDivElement | null>(null)
  const [overflow, setOverflow] = useState(false)

  useEffect(() => {
    const {
      clientHeight = 0,
      scrollHeight = 0,
    } = ref.current || {}
    const hasScroll = scrollHeight > clientHeight

    setOverflow(hasScroll)
  }, [ref.current?.clientHeight])

  if (isEmpty(matches)) return null

  return (
    <Fragment>
      <Title t='other_games' />
      <MatchesWrapper
        ref={ref}
        hasScroll={overflow}
        additionalScrollHeight={additionalScrollHeight}
      >
        {
          map(sortBy(matches, ({ live }) => !live), (match) => (
            <MatchCard
              key={match.id}
              match={match}
            />
          ))
        }
      </MatchesWrapper>
    </Fragment>
  )
}
