/**
 * @ai-summary React hooks for user preferences management
 * @ai-context Handles unit system, currency, and timezone preference sync with backend
 */

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useAuth0 } from '@auth0/auth0-react';
import { preferencesApi } from '../api/preferences.api';
import { UpdatePreferencesRequest } from '../types/preferences.types';
import toast from 'react-hot-toast';

interface ApiError {
  response?: {
    data?: {
      error?: string;
      message?: string;
    };
  };
  message?: string;
}

export const usePreferences = () => {
  const { isAuthenticated, isLoading } = useAuth0();

  return useQuery({
    queryKey: ['user-preferences'],
    queryFn: async () => {
      const response = await preferencesApi.getPreferences();
      return response.data;
    },
    enabled: isAuthenticated && !isLoading,
    staleTime: 5 * 60 * 1000, // 5 minutes
    gcTime: 10 * 60 * 1000, // 10 minutes cache time
    retry: (failureCount, error: any) => {
      // Retry 401s a few times (auth token might be refreshing)
      if (error?.response?.status === 401 && failureCount < 3) {
        return true;
      }
      return false;
    },
    retryDelay: (attemptIndex) => Math.min(1000 * 2 ** attemptIndex, 30000),
    refetchOnWindowFocus: false,
    refetchOnMount: false,
  });
};

export const useUpdatePreferences = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (data: UpdatePreferencesRequest) => preferencesApi.updatePreferences(data),
    onSuccess: (response) => {
      queryClient.setQueryData(['user-preferences'], response.data);
      // Don't show toast for unit system changes - context handles UI feedback
    },
    onError: (error: ApiError) => {
      const message = error.response?.data?.message || error.response?.data?.error || 'Failed to update preferences';
      toast.error(message);
    },
  });
};
