export const useOrderPolling = () => {
  const pollingInterval = ref<NodeJS.Timeout | null>(null)
  const lastOrderId = ref<number>(0)
  const isPolling = ref<boolean>(false)

  const startPolling = (
    fetchCallback: (lastId: number) => Promise<any[]>,
    onNewOrders: (orders: any[]) => void,
    intervalMs: number = 30000 // Default: 30 seconds
  ) => {
    if (isPolling.value) {
      console.warn('Polling is already active')
      return
    }

    isPolling.value = true

    pollingInterval.value = setInterval(async () => {
      try {
        const newOrders = await fetchCallback(lastOrderId.value)

        if (newOrders && newOrders.length > 0) {
          // Update the last order ID to the highest ID received
          const maxId = Math.max(...newOrders.map(order => order.id || 0))
          if (maxId > lastOrderId.value) {
            lastOrderId.value = maxId
            onNewOrders(newOrders)
          }
        }
      } catch (error) {
        console.error('Error polling for new orders:', error)
      }
    }, intervalMs)
  }

  const stopPolling = () => {
    if (pollingInterval.value) {
      clearInterval(pollingInterval.value)
      pollingInterval.value = null
      isPolling.value = false
    }
  }

  const setLastOrderId = (id: number) => {
    lastOrderId.value = id
  }

  // Clean up on unmount
  onUnmounted(() => {
    stopPolling()
  })

  return {
    startPolling,
    stopPolling,
    setLastOrderId,
    isPolling: readonly(isPolling),
    lastOrderId: readonly(lastOrderId)
  }
}
