import { useEffect, useState } from 'react';

import {
  createSoundDetector,
  StreamVideoParticipant,
} from '@stream-io/video-react-sdk';

const useAudioLevel = (participant: StreamVideoParticipant) => {
  const [audioLevel, setAudioLevel] = useState(0);

  useEffect(() => {
    const { audioStream } = participant;
    if (!audioStream) {
      setAudioLevel(0);
      return;
    }
    const disposeSoundDetector = createSoundDetector(
      audioStream,
      ({ audioLevel: level }) => setAudioLevel(level),
      { detectionFrequencyInMs: 0, destroyStreamOnStop: false },
    );
    return () => {
      disposeSoundDetector();
    };
  }, [participant]);

  return { audioLevel };
};

export default useAudioLevel;
