import { useContext } from 'react';
import { SpotifyContext } from '@/contexts/spotify-context';
import type { SpotifyContextType } from './types';

export const useSpotify = (): SpotifyContextType | null => {
  const context = useContext(SpotifyContext);
  return context;
};

export const useSpotifyAuth = () => {
  const context = useSpotify();

  if (!context) {
    return {
      isAuthenticated: false,
      login: async () => {},
      logout: async () => {},
    };
  }

  const { isAuthenticated, login, logout } = context;
  return { isAuthenticated, login, logout };
};

export const useSpotifyPlayback = () => {
  const context = useSpotify();

  if (!context) {
    return {
      playbackState: null,
      currentTrack: null,
      play: async () => {},
      playTrack: async () => {},
      pause: async () => {},
      skipNext: async () => {},
      skipPrevious: async () => {},
      setVolume: async () => {},
      refreshPlaybackState: async () => {},
      isLoading: false,
      isPlaying: false,
    };
  }

  const {
    playbackState,
    currentTrack,
    play,
    playTrack,
    pause,
    skipNext,
    skipPrevious,
    setVolume,
    refreshPlaybackState,
    isLoading,
  } = context;

  return {
    playbackState,
    currentTrack,
    play,
    playTrack,
    pause,
    skipNext,
    skipPrevious,
    setVolume,
    refreshPlaybackState,
    isLoading,
    isPlaying: playbackState?.is_playing || false,
  };
};

export const useSpotifyDevices = () => {
  const context = useSpotify();

  if (!context) {
    return {
      devices: [],
      activeDevice: null,
      getDevices: async () => {},
      setActiveDevice: async () => {},
      isLoading: false,
    };
  }

  const {
    devices,
    activeDevice,
    getDevices,
    setActiveDevice,
    isLoading,
  } = context;

  return {
    devices,
    activeDevice,
    getDevices,
    setActiveDevice,
    isLoading,
  };
};
