import {
  useCallback,
  useRef,
} from 'react'
import { useLocation } from 'react-router'

import { LogActions, logUserAction } from 'requests/logUserAction'

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

import { PlaylistOption, PlaylistTypes } from 'features/MatchPage/types'

const playlistTypeConfig = {
  ball_in_play: 2,
  full_game: 1,
  goals: 4,
  highlights: 3,
  players: 5,
}

const getInitialData = () => ({ dateVisit: new Date().toISOString(), seconds: 0 })

export const usePlayerLogger = () => {
  const location = useLocation()
  const { profileId, sportType } = usePageParams()
  const data = useRef(getInitialData())

  const incrementSeconds = () => data.current.seconds++

  const resetData = () => {
    data.current = getInitialData()
  }

  const { start, stop } = useInterval({
    callback: incrementSeconds,
    intervalDuration: 1000,
    startImmediate: false,
  })

  const onPlayingChange = useCallback((playing: boolean) => {
    if (playing) {
      start()
    } else {
      stop()
    }
  }, [start, stop])

  const logPlaylistChange = (prevPlaylist: PlaylistOption) => {
    const args = prevPlaylist.type === PlaylistTypes.MATCH
      ? {
        playlistType: playlistTypeConfig[prevPlaylist.id],
      }
      : {
        playerId: prevPlaylist.id,
        playlistType: playlistTypeConfig.players,
      }

    logUserAction({
      actionType: LogActions.VideoChange,
      dateVisit: data.current.dateVisit,
      duration: data.current.seconds,
      matchId: profileId,
      sportType,
      url: location.pathname,
      ...args,
    })
    resetData()
  }

  return { logPlaylistChange, onPlayingChange }
}
