import { AVPlaybackSource, AVPlaybackStatus, Audio } from "expo-av";
import { useFocusEffect } from "expo-router";
import { useCallback, useEffect, useState } from "react";
import { set } from 'react-hook-form';

interface AudioPlayerProps {
    source: AVPlaybackSource;
}

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

    const onPlaybackStatusUpdate = (status: AVPlaybackStatus) => {
        status.isLoaded && setPosition(status.positionMillis);
    }

    const onValueChange = (value: number) => {
        if (sound) {
            sound.setPositionAsync(value);
        }
    }

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

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

    const onUnmount = useCallback(() => {
        sound?.unloadAsync();
    }, [sound]);

    useEffect(() => {
        loadAudio();
        return () => {
            onUnmount();
        }
    }, []);

    return { togglePlay, isPlaying, duration, position, onValueChange, onUnmount };
}