import { useQuery } from '@tanstack/react-query';
import { AnalyticsApi, AnalyticsParams } from '@/lib/analyticsApi';
import { useDashboardPeriod } from './useDashboardPeriod';

/**
 * Hook for fetching analytics data with automatic period handling
 * Falls back to dummy data when useDummy is true
 */

export function useAnalytics<T>(
  endpoint: keyof typeof AnalyticsApi,
  dummyData: T,
  additionalParams?: Partial<AnalyticsParams>
) {
  const { period, useDummy } = useDashboardPeriod();

  const { data, isLoading, error, refetch } = useQuery({
    queryKey: ['analytics', endpoint, period, additionalParams],
    queryFn: async () => {
      const params: AnalyticsParams = {
        period: period === 'all' ? undefined : period,
        ...additionalParams,
      };
      return await AnalyticsApi[endpoint](params);
    },
    enabled: !useDummy, // Only fetch when not using dummy data
    staleTime: 5 * 60 * 1000, // 5 minutes
    gcTime: 10 * 60 * 1000, // 10 minutes (formerly cacheTime)
    retry: false, // Don't retry failed API calls (backend not implemented yet)
  });

  // When using dummy data, never show error or loading
  // When using real data, show error only if API call was attempted and failed
  const result = {
    data: useDummy ? dummyData : (data as T || dummyData),
    isLoading: useDummy ? false : isLoading,
    error: useDummy ? null : error, // Clear error when switching to dummy mode
    refetch, // Expose refetch for retry functionality
  };

  return result;
}

/**
 * Specific hooks for each analytics endpoint
 */

export function useRevenueAnalytics(dummyData: any, granularity?: 'day' | 'week' | 'month') {
  return useAnalytics('revenue', dummyData, { granularity });
}

export function useOrdersAnalytics(dummyData: any) {
  return useAnalytics('orders', dummyData);
}

export function useProductsAnalytics(dummyData: any) {
  return useAnalytics('products', dummyData);
}

export function useCustomersAnalytics(dummyData: any) {
  return useAnalytics('customers', dummyData);
}

export function useCouponsAnalytics(dummyData: any) {
  return useAnalytics('coupons', dummyData);
}

export function useTaxesAnalytics(dummyData: any) {
  return useAnalytics('taxes', dummyData);
}

export function useOverviewAnalytics(dummyData: any) {
  return useAnalytics('overview', dummyData);
}
