import { useState, useEffect, useCallback } from 'react';
import { useQueryClient } from '@tanstack/react-query';
import { Alert, AlertQueryParams } from '../types/events';
import {
  useEvents,
  useEventsSummary,
  useAcknowledgeAlert,
  useResolveAlert,
  useCancelAutoAction,
  useBulkAcknowledgeAlerts,
  useBulkResolveAlerts
} from './useAlerts';
import { useSSEEvents } from '../../hooks/useSSE';
import { AlertFilterOptions, applyAlertFilters } from '../../utils/alertManagement';

interface UseUnifiedAlertsConfig {
  refetchInterval?: number;
  enableSSE?: boolean;
  sseChannels?: string[];
}

interface UseUnifiedAlertsReturn {
  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;
}

export function useUnifiedAlerts(
  tenantId: string,
  initialFilters: AlertFilterOptions = {},
  config: UseUnifiedAlertsConfig = {}
): UseUnifiedAlertsReturn {
  const [filters, setFilters] = useState<AlertFilterOptions>(initialFilters);
  const [search, setSearch] = useState('');

  // Fetch alerts and summary
  const {
    data: alertsData,
    isLoading,
    isRefetching,
    error,
    refetch
  } = useEvents(tenantId, filters as AlertQueryParams);

  const { data: summaryData } = useEventsSummary(tenantId);

  // Alert mutations
  const acknowledgeMutation = useAcknowledgeAlert({ tenantId });
  const resolveMutation = useResolveAlert({ tenantId });
  const cancelAutoActionMutation = useCancelAutoAction({ tenantId });
  const bulkAcknowledgeMutation = useBulkAcknowledgeAlerts({ tenantId });
  const bulkResolveMutation = useBulkResolveAlerts({ tenantId });

  // SSE connection for real-time updates
  const [isSSEConnected, setSSEConnected] = useState(false);
  const [sseError, setSSEError] = useState<Error | null>(null);

  // Enable SSE if configured
  if (config.enableSSE) {
    useSSEEvents({
      channels: config.sseChannels || [`*.alerts`, `*.notifications`],
    });
  }

  // Process alerts data
  const allAlerts: Alert[] = alertsData?.items || [];

  // Apply filters and search
  const filteredAlerts = applyAlertFilters(allAlerts, filters, search);

  // Mutation functions
  const handleAcknowledgeAlert = async (alertId: string) => {
    await acknowledgeMutation.mutateAsync(alertId);
    refetch();
  };

  const handleResolveAlert = async (alertId: string) => {
    await resolveMutation.mutateAsync(alertId);
    refetch();
  };

  const handleCancelAutoAction = async (alertId: string) => {
    await cancelAutoActionMutation.mutateAsync(alertId);
  };

  const handleAcknowledgeAlertsByMetadata = async (alertType: string, metadata: any) => {
    await bulkAcknowledgeMutation.mutateAsync({
      alertType,
      metadataFilter: metadata
    });
    refetch();
  };

  const handleResolveAlertsByMetadata = async (alertType: string, metadata: any) => {
    await bulkResolveMutation.mutateAsync({
      alertType,
      metadataFilter: metadata
    });
    refetch();
  };

  return {
    alerts: allAlerts,
    filteredAlerts,
    stats: summaryData,
    filters,
    setFilters,
    search,
    setSearch,
    isLoading,
    isRefetching,
    error: error || null,
    refetch,
    acknowledgeAlert: handleAcknowledgeAlert,
    resolveAlert: handleResolveAlert,
    cancelAutoAction: handleCancelAutoAction,
    acknowledgeAlertsByMetadata: handleAcknowledgeAlertsByMetadata,
    resolveAlertsByMetadata: handleResolveAlertsByMetadata,
    isSSEConnected,
    sseError,
  };
}

// Additional hooks that may be used with unified alerts
export function useSingleAlert(tenantId: string, alertId: string) {
  return useEvent(tenantId, alertId);
}

export function useAlertStats(tenantId: string) {
  return useEventsSummary(tenantId);
}

export function useRealTimeAlerts(tenantId: string, channels?: string[]) {
  const { notifications } = useSSEEvents({
    channels: channels || [`*.alerts`, `*.notifications`, `*.recommendations`],
  });

  return { realTimeAlerts: notifications };
}