import React, { useEffect, useRef } from 'react'
import { PositionalAudio, Box } from '@react-three/drei'
import { PositionalAudio as PositionalAudioImpl } from 'three'
import useStore from '../store'

type Props = JSX.IntrinsicElements['positionalAudio'] & {
  url: string
  distance?: number
  loop?: boolean
}

const ObraAudio: React.FC<Props> = ({ position, url, loop = true, ...props }) => {
  const pointerLocked = useStore((state) => state.pointerLocked)
  const audioRef = useRef<PositionalAudioImpl>()

  useEffect(() => {
    if (audioRef.current) {
      if (!pointerLocked && audioRef.current.isPlaying) {
        audioRef.current.pause()
      } else if (pointerLocked && !audioRef.current.isPlaying) {
        audioRef.current.play()
      }

      audioRef.current.setDirectionalCone(35, 60, 0.1)
      audioRef.current.setRefDistance(0.5)
    }
  }, [audioRef.current, pointerLocked])

  return (
    <group rotation={[0, -Math.PI / 2, 0]} position={[14, 1.6, 0]}>
      <PositionalAudio ref={audioRef} url={url} loop={loop} autoplay={false} {...props} />
    </group>
  )
}

export default ObraAudio
