import { useEffect } from 'react';
import TrackPlayer, {
  useProgress,
  usePlaybackState,
  useActiveTrack,
  State,
} from 'react-native-track-player';
import { usePlayerStore } from '../store/playerStore';
import { Track } from '../types';

// Hook to sync track player state with our store
export function usePlayerSync() {
  const { setIsPlaying, setCurrentTrack, setPosition, setDuration } =
    usePlayerStore();

  const playbackState = usePlaybackState();
  const progress = useProgress();
  const activeTrack = useActiveTrack();

  // Sync playback state
  useEffect(() => {
    const isPlaying =
      playbackState.state === State.Playing ||
      playbackState.state === State.Buffering;
    setIsPlaying(isPlaying);
  }, [playbackState.state, setIsPlaying]);

  // Sync progress
  useEffect(() => {
    setPosition(progress.position);
    setDuration(progress.duration);
  }, [progress.position, progress.duration, setPosition, setDuration]);

  // Sync active track
  useEffect(() => {
    if (activeTrack) {
      const track: Track = {
        id: activeTrack.id?.toString() || '',
        url: activeTrack.url?.toString() || '',
        title: activeTrack.title || 'Unknown',
        artist: activeTrack.artist,
        album: activeTrack.album,
        artwork: activeTrack.artwork,
        duration: activeTrack.duration,
        isLocal: !activeTrack.url?.toString().startsWith('http'),
      };
      setCurrentTrack(track);
    } else {
      setCurrentTrack(null);
    }
  }, [activeTrack, setCurrentTrack]);
}

// Hook for using player controls
export function usePlayerControls() {
  const {
    play,
    pause,
    skipToNext,
    skipToPrevious,
    seekTo,
    toggleShuffle,
    cycleRepeatMode,
    playTrack,
    playQueue,
    addToQueue,
  } = usePlayerStore();

  return {
    play,
    pause,
    skipToNext,
    skipToPrevious,
    seekTo,
    toggleShuffle,
    cycleRepeatMode,
    playTrack,
    playQueue,
    addToQueue,
  };
}

// Format seconds to mm:ss
export function formatTime(seconds: number): string {
  if (!seconds || isNaN(seconds)) return '0:00';
  const mins = Math.floor(seconds / 60);
  const secs = Math.floor(seconds % 60);
  return `${mins}:${secs.toString().padStart(2, '0')}`;
}
