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

import { useToggle } from 'hooks'

const useVolumeState = (videoRef: RefObject<HTMLVideoElement>) => {
  const [volume, setVolume] = useState(0.5)
  const setVideoVolume = useCallback((value: number) => {
    if (videoRef.current) {
      // eslint-disable-next-line no-param-reassign
      videoRef.current.volume = value
    }
    setVolume(value)
  }, [videoRef])
  return [volume, setVideoVolume] as const
}

export const useVolume = (videoRef: RefObject<HTMLVideoElement>) => {
  const {
    close: unmute,
    isOpen: muted,
    open: mute,
    toggle: toggleMuted,
  } = useToggle(true)
  const [volume, setVolume] = useVolumeState(videoRef)

  const onVolumeChange = (value: number) => {
    if (value === 0) {
      mute()
    } else {
      unmute()
    }
    setVolume(value)
  }

  const onVolumeClick = () => {
    if (muted && volume === 0) {
      setVolume(0.1)
    }
    toggleMuted()
  }

  return {
    muted,
    onVolumeChange,
    onVolumeClick,
    volume,
    volumeInPercent: volume * 100,
  }
}
