import { useEffect } from 'react'
import { useQueryClient } from '@tanstack/react-query'
import { useWebSocketContext } from '../components/WebSocketProvider'
import { useSnackbar } from '../contexts/SnackbarContext'

export function useRealtimeData() {
  const queryClient = useQueryClient()
  const { isConnected, lastMessage, subscribe } = useWebSocketContext()
  const { showInfo, showWarning } = useSnackbar()

  useEffect(() => {
    if (!isConnected) return

    // Subscribe to order updates
    const unsubscribeOrder = subscribe('order_update', (message) => {
      queryClient.invalidateQueries({ queryKey: ['orders'] })
      queryClient.invalidateQueries({ queryKey: ['balance'] })
      
      if (message.status === 'filled') {
        showInfo(`Order ${message.order_id} filled`)
      }
    })

    // Subscribe to position updates
    const unsubscribePosition = subscribe('position_update', (message) => {
      queryClient.invalidateQueries({ queryKey: ['positions'] })
      queryClient.invalidateQueries({ queryKey: ['portfolio'] })
    })

    // Subscribe to price updates
    const unsubscribePrice = subscribe('price_update', (message) => {
      // Invalidate market data queries for the specific symbol
      if (message.symbol) {
        queryClient.invalidateQueries({ queryKey: ['market-data', message.symbol] })
      }
    })

    // Subscribe to alert triggers
    const unsubscribeAlert = subscribe('alert_triggered', (message) => {
      queryClient.invalidateQueries({ queryKey: ['alerts'] })
      showWarning(`Alert triggered: ${message.alert_name || 'Unknown alert'}`)
    })

    // Subscribe to strategy signals
    const unsubscribeSignal = subscribe('strategy_signal', (message) => {
      queryClient.invalidateQueries({ queryKey: ['autopilot-status'] })
      if (message.signal_type) {
        showInfo(`Strategy signal: ${message.signal_type.toUpperCase()} for ${message.symbol || 'N/A'}`)
      }
    })

    // Subscribe to system events
    const unsubscribeSystem = subscribe('system_event', (message) => {
      if (message.event_type === 'error') {
        showWarning(`System event: ${message.message || 'Unknown error'}`)
      }
    })

    return () => {
      unsubscribeOrder()
      unsubscribePosition()
      unsubscribePrice()
      unsubscribeAlert()
      unsubscribeSignal()
      unsubscribeSystem()
    }
  }, [isConnected, subscribe, queryClient, showInfo, showWarning])
}

