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 'helpers'
import { prepareMatches } from 'helpers'
import { useAuthStore } from 'features/AuthStore'

import type { MatchInfo } from 'requests'
import { getTournamentMatches } from 'requests'

import { parseDate } from 'helpers/parseDate'

import { usePageParams } from 'hooks/usePageParams'

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

export const useTournamentData = (matchProfile: MatchInfo) => {
  const { sportType } = usePageParams()
  const { user } = useAuthStore()

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

  const tournamentId = matchProfile?.tournament.id ?? null

  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, user), ['date']))
      })()
    }
  }, [
    tournamentId,
    sportType,
    matchProfile?.live,
    matchProfile?.c_match_calc_status,
    user,
  ])

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

  return { tournamentData }
}
