import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { useAuth0 } from '@auth0/auth0-react';
import { fuelLogsApi } from '../api/fuel-logs.api';
import { CreateFuelLogRequest, FuelLogResponse, EnhancedFuelStats } from '../types/fuel-logs.types';

export const useFuelLogs = (vehicleId?: string) => {
  const { isAuthenticated, isLoading } = useAuth0();
  const queryClient = useQueryClient();

  const logsQuery = useQuery<FuelLogResponse[]>({
    queryKey: ['fuelLogs', vehicleId || 'all'],
    queryFn: () => (vehicleId ? fuelLogsApi.getFuelLogsByVehicle(vehicleId) : fuelLogsApi.getUserFuelLogs()),
    enabled: isAuthenticated && !isLoading,
    staleTime: 2 * 60 * 1000, // 2 minutes - fuel logs can be more fresh
    gcTime: 5 * 60 * 1000, // 5 minutes cache time
    retry: (failureCount, error: any) => {
      // Retry 401 errors up to 3 times for mobile auth timing issues
      if (error?.response?.status === 401 && failureCount < 3) {
        console.log(`[Mobile Auth] Fuel logs API retry ${failureCount + 1}/3 for 401 error`);
        return true;
      }
      return false;
    },
    retryDelay: (attemptIndex) => Math.min(1000 * 2 ** attemptIndex, 30000),
    refetchOnWindowFocus: false, // Prevent refetch on window focus
    refetchOnMount: false, // Only fetch on mount if data is stale
  });

  const statsQuery = useQuery<EnhancedFuelStats>({
    queryKey: ['fuelLogsStats', vehicleId],
    queryFn: () => fuelLogsApi.getVehicleStats(vehicleId!),
    enabled: !!vehicleId && isAuthenticated && !isLoading,
    retry: (failureCount, error: any) => {
      // Retry 401 errors up to 3 times for mobile auth timing issues
      if (error?.response?.status === 401 && failureCount < 3) {
        console.log(`[Mobile Auth] Fuel stats API retry ${failureCount + 1}/3 for 401 error`);
        return true;
      }
      return false;
    },
    retryDelay: (attemptIndex) => Math.min(1000 * 2 ** attemptIndex, 30000),
  });

  const createMutation = useMutation({
    mutationFn: (data: CreateFuelLogRequest) => fuelLogsApi.create(data),
    onSuccess: (_res, variables) => {
      queryClient.invalidateQueries({ queryKey: ['fuelLogs', variables.vehicleId] });
      queryClient.invalidateQueries({ queryKey: ['fuelLogs', 'all'] });
      queryClient.invalidateQueries({ queryKey: ['fuelLogsStats', variables.vehicleId] });
    },
  });

  return {
    fuelLogs: logsQuery.data,
    isLoading: logsQuery.isLoading || createMutation.isPending,
    error: logsQuery.error,
    stats: statsQuery.data,
    isStatsLoading: statsQuery.isLoading,
    createFuelLog: createMutation.mutateAsync,
  };
};

