import type { FormEvent } from 'react'
import {
  useEffect,
  useState,
} from 'react'

import format from 'date-fns/format'

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

import { usePageParams } from 'hooks/usePageParams'

import { useLexicsStore } from 'features/LexicsStore'
import { getName } from 'features/Name'
import { useAuthStore } from 'features/AuthStore'

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

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

  const teamName1 = getName({ nameObj: matchInfo?.team1 || {}, suffix })
  const teamName2 = getName({ nameObj: matchInfo?.team2 || {}, suffix })

  const date = matchInfo?.date
  const matchDate = (date && format(new Date(date), 'd MMM HH:mm')) || ''

  const { login } = useAuthStore()
  const handleSubmit = (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault()
    login()
  }

  useEffect(() => {
    getUnauthenticatedMatch(sportType, matchId).then(setMatchInfo)
  }, [sportType, matchId])

  return {
    handleSubmit,
    live: matchInfo?.live,
    matchDate,
    teamName1,
    teamName2,
  }
}
