import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { supabase } from '@/lib/supabaseClient';
import { handleError } from '@/lib/errorHandler';
import { toast } from 'sonner';

export interface SystemHealthData {
  orphaned_images_count: number;
  critical_alerts_count: number;
  high_alerts_count?: number;
  failed_webhook_count?: number;
  alerts_last_24h: number;
  checked_at: string;
}

export interface SystemAlert {
  id: string;
  alert_type: 'orphaned_images' | 'stale_submissions' | 'circular_dependency' | 'validation_error' | 'ban_attempt' | 'upload_timeout' | 'high_error_rate';
  severity: 'low' | 'medium' | 'high' | 'critical';
  message: string;
  metadata: Record<string, any> | null;
  resolved_at: string | null;
  created_at: string;
}

/**
 * Hook to fetch system health metrics
 * Only accessible to moderators and admins
 */
export function useSystemHealth() {
  return useQuery({
    queryKey: ['system-health'],
    queryFn: async () => {
      try {
        const { data, error } = await supabase
          .rpc('get_system_health');

        if (error) {
          handleError(error, {
            action: 'Fetch System Health',
            metadata: { error: error.message }
          });
          throw error;
        }

        return data?.[0] as SystemHealthData | null;
      } catch (error) {
        handleError(error, {
          action: 'Fetch System Health',
          metadata: { error: String(error) }
        });
        throw error;
      }
    },
    refetchInterval: 60000, // Refetch every minute
    staleTime: 30000, // Consider data stale after 30 seconds
  });
}

/**
 * Hook to fetch unresolved system alerts
 * Only accessible to moderators and admins
 */
export function useSystemAlerts(severity?: 'low' | 'medium' | 'high' | 'critical') {
  return useQuery({
    queryKey: ['system-alerts', severity],
    queryFn: async () => {
      try {
        let query = supabase
          .from('system_alerts')
          .select('*')
          .is('resolved_at', null)
          .order('created_at', { ascending: false });

        if (severity) {
          query = query.eq('severity', severity);
        }

        const { data, error } = await query;

        if (error) {
          handleError(error, {
            action: 'Fetch System Alerts',
            metadata: { severity, error: error.message }
          });
          throw error;
        }

        return (data || []) as SystemAlert[];
      } catch (error) {
        handleError(error, {
          action: 'Fetch System Alerts',
          metadata: { severity, error: String(error) }
        });
        throw error;
      }
    },
    refetchInterval: 30000, // Refetch every 30 seconds
    staleTime: 15000, // Consider data stale after 15 seconds
  });
}

/**
 * Hook to run system maintenance manually
 * Only accessible to admins
 */
export function useRunSystemMaintenance() {
  const queryClient = useQueryClient();
  
  return useMutation({
    mutationFn: async () => {
      const { data, error } = await supabase.rpc('run_system_maintenance');

      if (error) {
        handleError(error, {
          action: 'Run System Maintenance',
          metadata: { error: error.message }
        });
        throw error;
      }

      return data as Array<{
        task: string;
        status: 'success' | 'error';
        details: Record<string, any>;
      }>;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['system-health'] });
      queryClient.invalidateQueries({ queryKey: ['system-alerts'] });
      toast.success('System maintenance completed successfully');
    },
    onError: (error) => {
      handleError(error, {
        action: 'Run System Maintenance',
        metadata: { error: String(error) }
      });
      toast.error('Failed to run system maintenance');
    },
  });
}
