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

import type { Episodes, Videos } from 'requests'
import { getVideos } from 'requests'

import { usePageParams } from 'hooks/usePageParams'

import type { PlaylistOption } from 'features/MatchPage/types'

import { buildChapters } from '../helpers'

type Args = {
  episodes: Episodes,
  selectedPlaylist?: PlaylistOption,
}

export const useChapters = ({
  episodes,
  selectedPlaylist,
}: Args) => {
  const [videos, setVideos] = useState<Videos>([])
  const { profileId: matchId, sportType } = usePageParams()

  useEffect(() => {
    getVideos(sportType, matchId).then(setVideos)
  }, [sportType, matchId])

  const chapters = useMemo(
    () => buildChapters({
      episodes,
      selectedPlaylist,
      videos,
    }),
    [
      selectedPlaylist,
      episodes,
      videos,
    ],
  )

  return { chapters }
}
