import { useQuery } from '@tanstack/react-query';
import {
  getDashboardData,
  type DashboardStats,
  type RecentActivity,
  type LibraryPreview,
  type DashboardData,
} from '../services/dashboardService';

/**
 * Query key factory for dashboard queries
 * Action 2.1.1.7: Add React Query caching for dashboard endpoint
 */
export const dashboardQueryKeys = {
  all: ['dashboard'] as const,
  data: (options?: DashboardQueryOptions) =>
    [...dashboardQueryKeys.all, 'data', options] as const,
};

/**
 * Options for dashboard query
 */
export interface DashboardQueryOptions {
  activityLimit?: number;
  libraryLimit?: number;
  statsPeriod?: '7d' | '30d' | '90d' | 'all';
}

/**
 * Hook for fetching and managing dashboard data
 * FE-PAGE-001: Complete Dashboard page implementation
 * Action 2.1.1.7: Migrated to React Query for automatic caching
 */
export function useDashboard(
  options?: DashboardQueryOptions,
): {
  stats: DashboardStats | null;
  recentActivity: RecentActivity[];
  libraryPreview: LibraryPreview | null;
  isLoading: boolean;
  error: Error | null;
  refetch: () => Promise<void>;
} {
  const query = useQuery<DashboardData>({
    queryKey: dashboardQueryKeys.data(options),
    queryFn: () => getDashboardData(options),
    staleTime: 30 * 1000, // Consider data fresh for 30 seconds (dashboard data changes frequently)
    gcTime: 2 * 60 * 1000, // Keep in cache for 2 minutes (formerly cacheTime)
    retry: 1, // Retry once on failure
    retryDelay: 1000, // Wait 1 second before retry
  });

  // Extract data with defaults for backward compatibility
  const stats = query.data?.stats || null;
  const recentActivity = query.data?.recent_activity || [];
  const libraryPreview = query.data?.library_preview || null;

  return {
    stats,
    recentActivity,
    libraryPreview,
    isLoading: query.isLoading,
    error: query.error instanceof Error ? query.error : query.error ? new Error(String(query.error)) : null,
    refetch: async () => {
      await query.refetch();
    },
  };
}
