import { useQuery } from '@tanstack/react-query';
import { useLocation } from 'react-router-dom';
import { supabase } from '@/integrations/supabase/client';
import { queryKeys } from '@/lib/queryKeys';
import type { RecentAddition } from '@/types/database-stats';
import { useEffect } from 'react';

export function useRecentAdditions(limit: number = 50, entityTypeFilter?: string) {
  const location = useLocation();
  const isAdminPage = location.pathname.startsWith('/admin');

  const query = useQuery({
    queryKey: queryKeys.admin.recentAdditions(limit),
    queryFn: async () => {
      const { data, error } = await supabase.rpc('get_recent_additions', {
        limit_count: limit
      });

      if (error) {
        throw error;
      }

      return data as unknown as RecentAddition[];
    },
    enabled: isAdminPage, // Only run query on admin pages
    staleTime: 2 * 60 * 1000, // 2 minutes
    refetchInterval: isAdminPage ? 30 * 1000 : false, // Only refetch on admin pages
  });

  // Set up real-time subscriptions
  useEffect(() => {
    const channels = [
      supabase
        .channel('recent_additions_parks')
        .on('postgres_changes', { event: 'INSERT', schema: 'public', table: 'parks' }, () => {
          query.refetch();
        })
        .subscribe(),
      supabase
        .channel('recent_additions_rides')
        .on('postgres_changes', { event: 'INSERT', schema: 'public', table: 'rides' }, () => {
          query.refetch();
        })
        .subscribe(),
      supabase
        .channel('recent_additions_companies')
        .on('postgres_changes', { event: 'INSERT', schema: 'public', table: 'companies' }, () => {
          query.refetch();
        })
        .subscribe(),
      supabase
        .channel('recent_additions_ride_models')
        .on('postgres_changes', { event: 'INSERT', schema: 'public', table: 'ride_models' }, () => {
          query.refetch();
        })
        .subscribe(),
      supabase
        .channel('recent_additions_photos')
        .on('postgres_changes', { event: 'INSERT', schema: 'public', table: 'photos' }, () => {
          query.refetch();
        })
        .subscribe(),
    ];

    return () => {
      channels.forEach(channel => channel.unsubscribe());
    };
  }, [query]);

  // Filter by entity type on client side
  const filteredData = entityTypeFilter && query.data
    ? query.data.filter(item => item.entity_type === entityTypeFilter)
    : query.data;

  return {
    ...query,
    data: filteredData,
  };
}
