import type { RefObject } from 'react'
import { useState, useCallback } from 'react'

import { preparePlayer } from '../helpers'

export const usePlayingState = (videoRef: RefObject<HTMLVideoElement>) => {
  const [firstTimeStart, setFirstTimeStart] = useState(true)
  const [playing, setPlaying] = useState(false)

  const togglePlaying = useCallback(() => {
    setPlaying((isPlaying) => {
      const video = videoRef.current
      if (!video || firstTimeStart) return false

      const nextIsPlaying = !isPlaying
      if (nextIsPlaying) {
        video.play()
      } else {
        video.pause()
      }
      return nextIsPlaying
    })
  }, [firstTimeStart, videoRef])

  const stopPlaying = useCallback((nextUrl: string = '') => {
    preparePlayer({ url: nextUrl, videoRef })
    setPlaying(false)
  }, [videoRef])

  const startPlaying = useCallback((url: string, from?: number) => {
    preparePlayer({
      from,
      url,
      videoRef,
    })
    videoRef.current?.play()
    setFirstTimeStart(false)
    setPlaying(true)
  }, [videoRef])

  const continuePlaying = useCallback((
    url: string,
    from?: number,
  ) => {
    preparePlayer({
      from,
      url,
      videoRef,
    })

    setPlaying((isPlaying) => {
      if (isPlaying) {
        videoRef.current?.play()
      }
      return isPlaying
    })
  }, [videoRef])

  return {
    continuePlaying,
    firstTimeStart,
    playing,
    startPlaying,
    stopPlaying,
    togglePlaying,
  }
}
