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

import { client } from 'config/clients'

import map from 'lodash/map'

import {
  getTournaments,
  Tournament,
} from 'requests/getTournaments'
import { getTeams, Team } from 'requests/getTeams'
import { Tournaments } from 'requests/getSportTournaments'

import {
  tournamentsId,
  teamsId,
  sportId,
} from '../../config'

export const useTournamentPopup = () => {
  const [isOpen, setIsOpen] = useState(false)
  const [isFetching, setFetching] = useState(true)
  const [tournaments, setTournaments] = useState<Tournaments>([])
  const [teams, setTeams] = useState<Tournaments>([])

  const close = () => setIsOpen(false)
  const open = () => setIsOpen(true)

  const sortTournaments = (tournamentsData: Tournaments) => {
    const data = new Map()
    tournamentsData.forEach((tourn) => data.set(tourn.id, tourn))
    const result = tournamentsId.map((id) => ({ ...data.get(id) }))
    return result
  }

  const convertData = useCallback(
    (data: Array<Tournament> | Array<Team>) => map(
      data,
      (tournament) => ({
        gender: null,
        sport: sportId,
        tournament_type: sportId,
        ...tournament,
      }),
    ),
    [],
  )
  useEffect(() => {
    if (client.name === 'facr') {
      (async () => {
        Promise.all([
          getTournaments(1, tournamentsId).then(convertData),
          getTeams(1, teamsId).then(convertData),
        ])
          .then((data) => {
            // @ts-expect-error
            setTournaments(sortTournaments(data[0]))
            // @ts-expect-error
            setTeams(data[1])
            setFetching(false)
          })
      })()
    }
  }, [convertData])

  return {
    close,
    isFetching,
    isOpen,
    open,
    teams,
    tournaments,
  }
}
