import {
  SyntheticEvent,
  useEffect,
  useState,
  useRef,
} from 'react'
import { readToken } from 'helpers'

export const useAudioPlayer = (asset: string) => {
  const audio = useRef<HTMLAudioElement>(new Audio(''))
  const [playing, setPlaying] = useState(false)

  const toggle = (e: SyntheticEvent) => {
    e.preventDefault()
    e.stopPropagation()
    if (audio.current.paused) {
      audio.current.play()
      setPlaying(true)
    } else {
      audio.current.pause()
      setPlaying(false)
    }
  }

  useEffect(() => {
    setPlaying(false)
    audio.current?.pause()
    audio.current = new Audio(`${asset}?access_token=${readToken()}`)
  }, [asset])

  useEffect(() => {
    audio.current?.addEventListener('ended', () => audio.current.pause())
    return () => {
      audio.current?.removeEventListener('ended', () => audio.current.pause())
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  return { playing, toggle }
}
