import {
  useCallback,
  useEffect,
  useState,
} from 'react'

import isEmpty from 'lodash/isEmpty'
import filter from 'lodash/filter'

import type { LiveVideos, Videos } from 'requests'
import { getLiveVideos, getVideos } from 'requests'

import { useSportNameParam, usePageId } from 'hooks'

import { useLastPlayPosition } from './useLastPlayPosition'

const filterByIds = (videos: Videos) => {
  const zeroIdVideos = filter(videos, { abc: '0' })
  return isEmpty(zeroIdVideos) ? videos : zeroIdVideos
}

export const useVideoData = () => {
  const [videos, setVideos] = useState<Videos>([])
  const [liveVideos, setLiveVideos] = useState<LiveVideos>([])
  const { sportType } = useSportNameParam()
  const matchId = usePageId()

  const fetchMatchVideos = useCallback(async () => {
    const videosResponse = await getVideos(sportType, matchId)
    const filteredVideosResponseByAbc = filterByIds(videosResponse)
    setVideos(filteredVideosResponseByAbc)
  }, [sportType, matchId])

  useEffect(() => {
    getLiveVideos(sportType, matchId)
      .then(setLiveVideos)
      .catch(fetchMatchVideos)
  },
  [
    sportType,
    matchId,
    fetchMatchVideos,
  ])

  return {
    url: liveVideos[0] || '',
    videos,
    ...useLastPlayPosition(),
  }
}
