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

import { format } from 'date-fns'
import sortedUniq from 'lodash/sortedUniq'
import isNull from 'lodash/isNull'
import sortBy from 'lodash/sortBy'

import type { Match } from 'features/Matches'
import { prepareMatches } from 'features/Matches/helpers/prepareMatches'

import { getTournamentMatches } from 'requests'

import { parseDate } from 'helpers/parseDate'

import { usePageParams } from 'hooks/usePageParams'

import { TournamentData } from '../../types'

export const useTournamentData = (tournamentId: number | null) => {
  const { sportType } = usePageParams()

  const [tournamentMatches, setTournamentMatches] = useState<Array<Match>>([])
  const [matchDates, setMatchDates] = useState<Array<string>>([])

  useEffect(() => {
    if (!isNull(tournamentId)) {
      (async () => {
        const matchesBySection = await getTournamentMatches({
          limit: 1000,
          offset: 0,
          sportType,
          tournamentId,
        })

        const matchDateList = matchesBySection.broadcast.map((match) => (
          parseDate(match.date)
        )).sort((a, b) => a.getTime() - b.getTime())

        setMatchDates(sortedUniq(matchDateList.map((date) => format(date, 'yyyy-MM-dd'))))
        setTournamentMatches(sortBy(prepareMatches(matchesBySection.broadcast), ['date']))
      })()
    }
  }, [tournamentId, sportType])

  const tournamentData: TournamentData = useMemo(() => ({
    matchDates,
    matches: tournamentMatches,
  }), [matchDates, tournamentMatches])

  return { tournamentData }
}
