import { useCallback } from 'react';
import { useQueryClient } from '@tanstack/react-query';
import { favoritesService } from '../services/favoritesService';
import { quarantineService } from '../services/quarantineService';
import { toast } from '../store/useToastStore';

/**
 * Returns a stable `dislikeTrack` callback that:
 * 1. POSTs the dislike to the API
 * 2. Invalidates the dislikes query
 * 3. Shows an undo-able toast
 * 4. On undo: restores the track + invalidates queries
 *
 * Extracted because the exact same flow was duplicated in TrackRow and PlaybackBar.
 */
export function useDislikeTrack() {
  const qc = useQueryClient();

  const dislikeTrack = useCallback(
    (trackId: string) => {
      void favoritesService
        .dislike(trackId)
        .then(() => {
          qc.invalidateQueries({ queryKey: ['dislikes'] });
          toast.info('Moved to quarantine. Will be deleted after the grace period.', {
            ttl: 7000,
            action: {
              label: 'Undo',
              onClick: () => {
                void quarantineService
                  .restore(trackId)
                  .then(() => {
                    qc.invalidateQueries({ queryKey: ['dislikes'] });
                    qc.invalidateQueries({ queryKey: ['tracks'] });
                    toast.success('Track restored to library');
                  })
                  .catch(() => toast.error("Couldn't undo. Restore it from Quarantine."));
              },
            },
          });
        })
        .catch(() => toast.error("Couldn't dislike this track. Try again."));
    },
    [qc],
  );

  return dislikeTrack;
}
