import { useState, useEffect } from 'react';

import { Howl } from 'howler';

const useBrowserMedia = (jamTrack) => {
  const [audio, setAudio] = useState(null);
  const [loaded, setLoaded] = useState(false);
  const [loading, setLoading] = useState(false);
  const [playing, setPlaying] = useState(false);
  const [paused, setPaused] = useState(false);
  const [loadError, setLoadError] = useState(false);
  const [playPosition, setPlayPosition] = useState(0);
  //const [error, setError] = useState(null);
  const preLoad = true;

  const manageMixdownSync = () => {
    const activeMixdown = jamTrack.mixdowns.find(mixdown => mixdown.id === jamTrack.last_mixdown_id)

    const activeStem = jamTrack.tracks.find(stem => stem.id === jamTrack.last_stem_id);

    if ( activeStem ) {
    } else if ( activeMixdown ) {
    } else if (jamTrack) {
      const masterTrack = jamTrack.tracks.find(track => track.track_type === 'Master');
      if (masterTrack) {
        loadMedia([masterTrack.preview_mp3_url]);
      }
    }

  }

  useEffect(() => {
    if (!jamTrack) {
      return;
    }
    manageMixdownSync();
   
  }, [jamTrack]);

  useEffect(() => {
    if (playing) {
      const interval = setInterval(() => {
        if (audio) {
          const position = audio.seek();
          if(position === audio) {
            setPlayPosition(0);
          }else{

          }
        }
      }, 500);
      return () => clearInterval(interval);
    }
  }, [playing]);

  const loadMedia = (urls) => {
    if (audio) {
      audio.unload();
    }
    setLoading(true);
    setAudio(new Howl({
      src: urls,
      autoplay: false,
      loop: false,
      volume: 1,
      preload: true,
      onstop: () => {
        console.log('Audio stopped');
        setLoading(false);
        setPlaying(false);
        setPaused(false);
      },
      onend: () => {
        alert('Audio ended')
        console.log('Audio ended');
        setLoading(false);
        setPlaying(false);
        setPaused(false);
      
      },
      onload: () => {
        console.log('Audio loaded');
        setLoading(false);
        setLoaded(true);
      },
      onloaderror: () => {
        console.log('Audio load error');
        setLoading(false);
        setLoadError(true);
      },
      onpause: () => {
        console.log('Audio paused');
        setPaused(true);
        setPlaying(false);
      },
      onplay: () => {
        console.log('Audio playing');
        setPlaying(true);
        setPaused(false);
      }
    }));
  }

  const play = () => {
    if (audio) {
      audio.play();
    }
  }

  const stop = () => {
    if (audio) {
      try {
        audio.pause();
        audio.seek(0);
      } catch (error) {
        console.log('Error stopping audio', error);
      }
    }
  }

  const pause = () => {
    if (audio) {
      audio.pause();
    }
  }

  return { play, stop, pause, loading, loaded, playing, paused, loadError, playPosition };
};

export default useBrowserMedia;