import type { TournamentInfo } from 'requests'

import { useEffect, useState } from 'react'

import { useHeaderFiltersStore } from 'features/HeaderFilters'
import { useLexicsStore } from 'features/LexicsStore'

import { getTournamentInfo } from 'requests'

import { useSportNameParam, usePageId } from 'hooks'

type Name = 'name_rus' | 'name_eng'

export const useTournamentPage = () => {
  const [tournamentProfile, setTournamentProfile] = useState<TournamentInfo>(null)
  const { sportType } = useSportNameParam()
  const pageId = usePageId()
  const { suffix } = useLexicsStore()

  const {
    setSelectedSportTypeId,
    setSelectedTournamentId,
  } = useHeaderFiltersStore()

  const {
    [`name_${suffix}` as Name]: name = '',
  } = tournamentProfile || {}

  const {
    [`name_${suffix}` as Name]: country = '',
  } = tournamentProfile?.country || {}

  useEffect(() => {
    getTournamentInfo(sportType, pageId)
      .then(setTournamentProfile)
    setSelectedSportTypeId(sportType)
    setSelectedTournamentId(pageId)

    return () => {
      setSelectedSportTypeId(null)
      setSelectedTournamentId(null)
    }
  }, [pageId,
    setSelectedSportTypeId,
    setSelectedTournamentId,
    sportType,
  ])

  return {
    infoItems: [country],
    name,
  }
}
