import {
  useEffect,
  useState,
} from 'react'

import format from 'date-fns/format'

import type { UnauthenticatedMatch } from 'requests'
import { getUnauthenticatedMatch } from 'requests'

import { parseDate } from 'helpers/parseDate'

import { usePageParams } from 'hooks/usePageParams'

import { useAuthStore } from 'features/AuthStore'

export const useUnauthenticatedMatch = () => {
  const { login } = useAuthStore()

  const [
    matchInfo, setMatchInfo,
  ] = useState<UnauthenticatedMatch>(null)

  const { profileId: matchId, sportType } = usePageParams()

  const matchDate = matchInfo?.date
    ? format(parseDate(matchInfo.date), 'd MMM HH:mm')
    : ''

  useEffect(() => {
    if (sportType && matchId) getUnauthenticatedMatch(sportType, matchId).then(setMatchInfo)

    return () => setMatchInfo(null)
  }, [sportType, matchId])

  return {
    live: matchInfo?.live,
    matchDate,
    matchInfo,
    onJoinClick: login,
  }
}
