import { useQuery } from '@tanstack/react-query'
import { marketDataApi, ProviderStatus } from '../api/marketData'
import { useWebSocketContext } from '../components/WebSocketProvider'
import { useEffect, useState } from 'react'

export interface ProviderStatusData {
  status: ProviderStatus | null
  isLoading: boolean
  error: Error | null
  refetch: () => void
}

export function useProviderStatus(): ProviderStatusData {
  const { isConnected, lastMessage } = useWebSocketContext()
  const [status, setStatus] = useState<ProviderStatus | null>(null)

  const {
    data,
    isLoading,
    error,
    refetch,
  } = useQuery({
    queryKey: ['provider-status'],
    queryFn: () => marketDataApi.getProviderStatus(),
    refetchInterval: 10000, // Refetch every 10 seconds
  })

  // Update local state when query data changes
  useEffect(() => {
    if (data) {
      setStatus(data)
    }
  }, [data])

  // Listen for provider status updates via WebSocket
  useEffect(() => {
    if (!isConnected || !lastMessage) return

    try {
      const message = typeof lastMessage === 'string' ? JSON.parse(lastMessage) : lastMessage
      
      if (message.type === 'provider_status_update') {
        // Update status from WebSocket message
        setStatus((prev) => ({
          ...prev!,
          ...message.data,
        }))
      }
    } catch (e) {
      // Ignore parsing errors
    }
  }, [isConnected, lastMessage])

  return {
    status,
    isLoading,
    error: error as Error | null,
    refetch,
  }
}
