/**
 * Unified Alert Context
 * 
 * Context provider for sharing alert state across components
 */

import React, { createContext, useContext, ReactNode, useState, useEffect, useCallback } from 'react';
import { Alert } from '../api/types/events';
import { useUnifiedAlerts } from '../api/hooks/useUnifiedAlerts';
import { AlertFilterOptions } from '../utils/alertManagement';

// Define context type
interface AlertContextType {
  alerts: Alert[];
  filteredAlerts: Alert[];
  stats: any;
  filters: AlertFilterOptions;
  setFilters: (filters: AlertFilterOptions) => void;
  search: string;
  setSearch: (search: string) => void;
  isLoading: boolean;
  isRefetching: boolean;
  error: Error | null;
  refetch: () => void;
  acknowledgeAlert: (alertId: string) => Promise<void>;
  resolveAlert: (alertId: string) => Promise<void>;
  cancelAutoAction: (alertId: string) => Promise<void>;
  acknowledgeAlertsByMetadata: (alertType: string, metadata: any) => Promise<void>;
  resolveAlertsByMetadata: (alertType: string, metadata: any) => Promise<void>;
  isSSEConnected: boolean;
  sseError: Error | null;
}

// Create context with default values
const AlertContext = createContext<AlertContextType | undefined>(undefined);

// Props for the provider
interface AlertProviderProps {
  children: ReactNode;
  tenantId: string;
  initialFilters?: AlertFilterOptions;
}

// Alert Provider Component
export const AlertProvider: React.FC<AlertProviderProps> = ({ 
  children, 
  tenantId, 
  initialFilters = {} 
}) => {
  // Use the unified hook
  const unifiedAlerts = useUnifiedAlerts(tenantId, initialFilters, {
    refetchInterval: 60000, // 1 minute
    enableSSE: true,
    sseChannels: [`*.alerts`, `*.notifications`]
  });

  return (
    <AlertContext.Provider value={unifiedAlerts}>
      {children}
    </AlertContext.Provider>
  );
};

// Custom hook to use the alert context
export const useAlertContext = (): AlertContextType => {
  const context = useContext(AlertContext);
  if (context === undefined) {
    throw new Error('useAlertContext must be used within an AlertProvider');
  }
  return context;
};

// Export the context for use in components
export default AlertContext;