import { useEffect, useState } from "react";
import { Audio } from 'expo-av';
import { Sound } from 'expo-av/build/Audio';

export function useAudio(soundFile: any, soundEnabled: boolean) {
  const [sound, setSound] = useState<Sound | null>(null);

  useEffect(() => {
    const configureAudio = async () => {
      await Audio.setAudioModeAsync({
        allowsRecordingIOS: false,
        staysActiveInBackground: true,
        playsInSilentModeIOS: true,
        shouldDuckAndroid: true,
        playThroughEarpieceAndroid: false,
      });
    };

    if (soundEnabled) {
      configureAudio();
    }

    return () => {
      if (sound) {
        sound.unloadAsync();
      }
    };
  }, [soundEnabled]);

  async function playSound() {
    if (!soundEnabled) return;

    const { sound } = await Audio.Sound.createAsync(soundFile);
    setSound(sound);

    await sound.playAsync();
  }

  useEffect(() => {
    return sound
      ? () => {
        sound.unloadAsync();
      }
      : undefined;
  }, [sound]);

  return { playSound };
}
