import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import {
  createPlaylist,
  getPlaylist,
  updatePlaylist,
  deletePlaylist,
  listPlaylists,
  addCollaborator,
  removeCollaborator,
  updateCollaboratorPermission,
  addTrackToPlaylist,
  getCollaborators,
  createShareLink,
  reorderPlaylistTracks,
  PlaylistCollaborator,
  AddCollaboratorRequest,
  UpdateCollaboratorPermissionRequest,
} from '../services/playlistService';
import type {
  Playlist,
  CreatePlaylistRequest,
  UpdatePlaylistRequest,
} from '../types';
import { TokenStorage } from '@/services/tokenStorage';

// Create Playlist
export function useCreatePlaylist() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (data: CreatePlaylistRequest) => createPlaylist(data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['playlists'] });
    },
  });
}

// Get Playlist
export function usePlaylist(id: string) {
  return useQuery({
    queryKey: ['playlist', id],
    queryFn: () => getPlaylist(id),
    enabled: !!id,
  });
}

// Update Playlist
export function useUpdatePlaylist() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: ({ id, data }: { id: string; data: UpdatePlaylistRequest }) =>
      updatePlaylist(id, data),
    onSuccess: (data: Playlist) => {
      queryClient.invalidateQueries({ queryKey: ['playlist', data.id] });
      queryClient.invalidateQueries({ queryKey: ['playlists'] });
    },
  });
}

// Delete Playlist
export function useDeletePlaylist() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (id: string) => deletePlaylist(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['playlists'] });
    },
  });
}

// List Playlists
export function usePlaylists(limit = 20, offset = 0) {
  // Check if token exists in storage (more reliable than waiting for store hydration)
  const hasToken = !!TokenStorage.getAccessToken();
  const page = Math.floor(offset / limit) + 1;

  return useQuery({
    queryKey: ['playlists', limit, offset],
    queryFn: () => listPlaylists(page, limit),
    enabled: hasToken, // Only fetch if token exists
  });
}

// Add Collaborator
export function useAddCollaborator() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: ({
      playlistId,
      data,
    }: {
      playlistId: string;
      data: AddCollaboratorRequest;
    }) => addCollaborator(playlistId, data),
    onSuccess: (data: PlaylistCollaborator) => {
      queryClient.invalidateQueries({
        queryKey: ['playlist', data.playlist_id],
      });
      queryClient.invalidateQueries({
        queryKey: ['playlist', data.playlist_id, 'collaborators'],
      });
      queryClient.invalidateQueries({ queryKey: ['playlists'] });
    },
  });
}

// Remove Collaborator
export function useRemoveCollaborator() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: ({
      playlistId,
      userId,
    }: {
      playlistId: string;
      userId: string;
    }) => removeCollaborator(playlistId, userId),
    onSuccess: (_, variables) => {
      queryClient.invalidateQueries({
        queryKey: ['playlist', variables.playlistId],
      });
      queryClient.invalidateQueries({
        queryKey: ['playlist', variables.playlistId, 'collaborators'],
      });
      queryClient.invalidateQueries({ queryKey: ['playlists'] });
    },
  });
}

// Update Collaborator Permission
export function useUpdateCollaboratorPermission() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: ({
      playlistId,
      userId,
      data,
    }: {
      playlistId: string;
      userId: string;
      data: UpdateCollaboratorPermissionRequest;
    }) => updateCollaboratorPermission(playlistId, userId, data),
    onSuccess: (_, variables) => {
      queryClient.invalidateQueries({
        queryKey: ['playlist', variables.playlistId],
      });
      queryClient.invalidateQueries({
        queryKey: ['playlist', variables.playlistId, 'collaborators'],
      });
      queryClient.invalidateQueries({ queryKey: ['playlists'] });
    },
  });
}

// Create Share Link
export function useCreateShareLink() {
  return useMutation({
    mutationFn: (id: string) => createShareLink(id),
  });
}

// Reorder Playlist Tracks
export function useReorderPlaylistTracks() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: ({
      playlistId,
      trackIds,
    }: {
      playlistId: string;
      trackIds: string[];
    }) => reorderPlaylistTracks(playlistId, { track_ids: trackIds }),
    onSuccess: (_, variables) => {
      queryClient.invalidateQueries({
        queryKey: ['playlist', variables.playlistId],
      });
    },
  });
}

// Get Collaborators
export function useCollaborators(playlistId: string) {
  return useQuery({
    queryKey: ['playlist', playlistId, 'collaborators'],
    queryFn: () => getCollaborators(playlistId),
    enabled: !!playlistId,
  });
}

// Add Track to Playlist
export function useAddTrackToPlaylist() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: ({
      playlistId,
      trackId,
    }: {
      playlistId: string;
      trackId: string;
    }) => addTrackToPlaylist(playlistId, trackId),
    onSuccess: (_, variables) => {
      queryClient.invalidateQueries({
        queryKey: ['playlist', variables.playlistId],
      });
      queryClient.invalidateQueries({ queryKey: ['playlists'] }); // Update track counts in list
    },
  });
}
