import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
	deleteDashboardShortcut,
	fetchActivity,
	fetchCounts,
	fetchDashboardShortcuts,
	fetchLibraries,
	saveDashboardShortcut,
} from "../api/client";
import type { DashboardShortcutInput } from "../types";

export function useCounts(jellyfinServiceId?: string) {
	return useQuery({
		queryKey: ["dashboard", "counts", jellyfinServiceId ?? "default"],
		queryFn: () => fetchCounts(jellyfinServiceId),
		staleTime: 5 * 60 * 1000,
	});
}

export function useLibraries(jellyfinServiceId?: string) {
	return useQuery({
		queryKey: ["dashboard", "libraries", jellyfinServiceId ?? "default"],
		queryFn: () => fetchLibraries(jellyfinServiceId),
		staleTime: 5 * 60 * 1000,
	});
}

export function useActivity(jellyfinServiceId?: string) {
	return useQuery({
		queryKey: ["dashboard", "activity", jellyfinServiceId ?? "default"],
		queryFn: () => fetchActivity(jellyfinServiceId),
		refetchInterval: 15_000,
	});
}

// Backward-compatible alias used by older code.
export const useNowPlaying = useActivity;

export function useDashboardShortcuts() {
	return useQuery({
		queryKey: ["dashboard", "shortcuts"],
		queryFn: fetchDashboardShortcuts,
		refetchInterval: 30_000,
	});
}

export function useSaveDashboardShortcut() {
	const queryClient = useQueryClient();
	return useMutation({
		mutationFn: (shortcut: DashboardShortcutInput) =>
			saveDashboardShortcut(shortcut),
		onSuccess: () => {
			queryClient.invalidateQueries({ queryKey: ["dashboard", "shortcuts"] });
		},
	});
}

export function useDeleteDashboardShortcut() {
	const queryClient = useQueryClient();
	return useMutation({
		mutationFn: (shortcutId: string) => deleteDashboardShortcut(shortcutId),
		onSuccess: () => {
			queryClient.invalidateQueries({ queryKey: ["dashboard", "shortcuts"] });
		},
	});
}
