import { useEffect, useRef } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { useLocation } from 'react-router-dom'
import { apiClient } from '@/api/client'

/**
 * Global indexing heartbeat hook.
 *
 * Problem: The indexing "kick" mechanism previously only ran inside the
 * KnowledgeBase page. On many WordPress hosts, HTTP loopback is blocked
 * and WP-Cron is unreliable, so the admin UI kick was the only thing
 * driving indexing forward. Navigating away killed the polling.
 *
 * Solution: This hook is mounted in AdminLayout so it runs on ALL admin
 * pages. It polls `index/status` at a slow interval (20s) and kicks
 * the indexer when it detects a stall (pending > 0, processing === 0).
 *
 * On the Knowledge Base page itself, this hook is a no-op — the existing
 * fast polling (2s) and kick logic in KnowledgeBase.tsx takes over.
 */
export function useIndexingHeartbeat() {
  const location = useLocation()
  const queryClient = useQueryClient()
  const lastKickRef = useRef<number>(0)

  // Determine if we're on the Knowledge Base page.
  // If so, skip — the page's own faster polling handles it.
  const isOnKBPage = location.pathname === '/knowledge-base'

  // Lightweight status poll — only active when NOT on the KB page.
  const { data: statusData } = useQuery<{
    success: boolean
    data: {
      is_indexing: boolean
      paused?: boolean
      queue_stats?: {
        pending: number
        processing: number
      } | null
    }
  }>({
    queryKey: ['indexing-heartbeat', 'status'],
    queryFn: () => apiClient.get('index/status'),
    refetchInterval: isOnKBPage ? false : 20_000, // 20s when not on KB page
    enabled: !isOnKBPage,
    staleTime: 15_000,
    // Don't show errors in console for background polling
    retry: 0,
  })

  // Kick mutation — fire-and-forget.
  const kickMutation = useMutation({
    mutationFn: () => apiClient.post('index/kick'),
    onSuccess: () => {
      // Invalidate the main knowledge-base status so if the user
      // navigates to the KB page, they see fresh data.
      queryClient.invalidateQueries({ queryKey: ['knowledge-base', 'status'] })
    },
  })

  useEffect(() => {
    // Skip if we're on the KB page (its own watchdog handles it)
    if (isOnKBPage) return

    const status = statusData?.data
    if (!status) return

    // Only kick when: indexing active, not paused, items pending, nothing processing
    if (!status.is_indexing) return
    if (status.paused) return

    const pending = status.queue_stats?.pending ?? 0
    const processing = status.queue_stats?.processing ?? 0
    if (pending <= 0 || processing > 0) return

    // Throttle kicks to at most once every 20 seconds
    const now = Date.now()
    if (now - lastKickRef.current < 20_000) return

    lastKickRef.current = now
    kickMutation.mutate()
  }, [isOnKBPage, statusData, kickMutation])
}
