import { AVPlaybackSource, AVPlaybackStatus, Audio } from "expo-av";
import { useEffect, useState } from "react";

interface AudioPlayerProps {
    source: AVPlaybackSource;
}

export const useAudio = ({ source }: AudioPlayerProps) => {
    const [sound, setSound] = useState<Audio.Sound | null>(null);
    const [isPlaying, setIsPlaying] = useState(false);

    const loadAudio = async () => {
        const { sound, status } = await Audio.Sound.createAsync(source, {
            shouldPlay: false
        });
        if (status.isLoaded) {
            setSound(sound);
            setIsPlaying(status.isPlaying);
        }
    }

    const togglePlay = async () => {
        if (sound) {
            if (isPlaying) {
                await sound.pauseAsync();
            } else {
                await sound.playAsync();
            }
            setIsPlaying(!isPlaying);
        }
    }

    useEffect(() => {
        loadAudio();
        return () => {
            if (sound) {
                sound.pauseAsync();
                sound.unloadAsync();
            }
        }
    }, [source]);

    return { togglePlay, isPlaying };
}