import { useEffect, useState } from 'react'

import type { LastPlayPosition } from 'requests'
import { getMatchLastWatchSeconds } from 'requests'

import { usePageParams } from 'hooks/usePageParams'
import { useRequest } from 'hooks/useRequest'

const initialPosition = {
  half: 0,
  second: 0,
}

export const useLastPlayPosition = () => {
  const { profileId: matchId, sportType } = usePageParams()
  const [
    lastPlayPosition,
    setPosition,
  ] = useState<LastPlayPosition>(initialPosition)
  const {
    isFetching: isLastPlayPositionFetching,
    request: requestLastPlayPosition,
  } = useRequest(getMatchLastWatchSeconds)

  useEffect(() => {
    requestLastPlayPosition(sportType, matchId).then(setPosition)
  }, [
    sportType,
    matchId,
    requestLastPlayPosition,
  ])

  return {
    isLastPlayPositionFetching,
    lastPlayPosition,
  }
}
