import { useEffect, useState } from 'react';

const useVolume = (
  initialVolume: number,
  speakerUpdate: (volume: number) => void,
) => {
  const [showVolumeSlider, setShowVolumeSlider] = useState(false);
  const [volume, setVolume] = useState(initialVolume);
  const [previousVolume, setPreviousVolume] = useState(initialVolume);

  const muted = volume === 0;

  useEffect(() => {
    speakerUpdate(initialVolume);
  }, [speakerUpdate, initialVolume]);

  const handleVolumeButtonEnter = () => setShowVolumeSlider(true);

  const handleVolumeButtonLeave = () => setShowVolumeSlider(false);

  const handleVolumeChange = (event: Event, value: number | number[]) => {
    const newValue = Array.isArray(value) ? value[0] : value;
    speakerUpdate(newValue / 100);
    setVolume(newValue / 100);
  };

  const handleVolumeChangeCommitted = (
    event: Event | React.SyntheticEvent,
    newValue: number | number[],
  ) => {
    const value = Array.isArray(newValue) ? newValue[0] : newValue;
    if (value > 0) {
      setPreviousVolume(value / 100);
    }
  };

  const handleMuteChange = () => {
    if (volume === 0) {
      speakerUpdate(previousVolume || 0.5);
      setVolume(previousVolume || 0.5);
    } else {
      setPreviousVolume(volume);
      speakerUpdate(0);
      setVolume(0);
    }
  };

  return {
    volume,
    muted,
    showVolumeSlider,
    handleVolumeButtonEnter,
    handleVolumeButtonLeave,
    handleVolumeChange,
    handleVolumeChangeCommitted,
    handleMuteChange,
  };
};

export default useVolume;
