import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useServices } from '@/lib/services/ServiceProvider';
import { CompleteOnboardingInputDTO } from '@/lib/types/generated/CompleteOnboardingInputDTO';
import { DriverLeaderboardViewModel } from '@/lib/view-models/DriverLeaderboardViewModel';
import { DriverViewModel } from '@/lib/view-models/DriverViewModel';
import { DriverProfileViewModel } from '@/lib/view-models/DriverProfileViewModel';
import type { DriverDTO } from '@/lib/types/generated/DriverDTO';

export function useDriverLeaderboard() {
  const { driverService } = useServices();

  return useQuery({
    queryKey: ['driverLeaderboard'],
    queryFn: () => driverService.getDriverLeaderboard(),
  });
}

export function useCurrentDriver() {
  const { driverService } = useServices();

  return useQuery({
    queryKey: ['currentDriver'],
    queryFn: () => driverService.getCurrentDriver(),
  });
}

export function useDriverProfile(driverId: string) {
  const { driverService } = useServices();

  return useQuery({
    queryKey: ['driverProfile', driverId],
    queryFn: () => driverService.getDriverProfile(driverId),
    enabled: !!driverId,
  });
}

export function useCompleteDriverOnboarding() {
  const { driverService } = useServices();
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (input: CompleteOnboardingInputDTO) => driverService.completeDriverOnboarding(input),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['currentDriver'] });
    },
  });
}

export function useUpdateDriverProfile() {
  const { driverService } = useServices();
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (updates: { bio?: string; country?: string }) => driverService.updateProfile(updates),
    onSuccess: (data, variables) => {
      queryClient.invalidateQueries({ queryKey: ['driverProfile', data.currentDriver?.id] });
      queryClient.invalidateQueries({ queryKey: ['currentDriver'] });
    },
  });
}

export function useFindDriverById(id: string) {
  const { driverService } = useServices();

  return useQuery({
    queryKey: ['driver', id],
    queryFn: () => driverService.findById(id),
    enabled: !!id,
  });
}

export function useFindDriversByIds(ids: string[]) {
  const { driverService } = useServices();

  return useQuery({
    queryKey: ['drivers', ids],
    queryFn: () => driverService.findByIds(ids),
    enabled: ids.length > 0,
  });
}