import { useEffect, useRef } from 'react'
import { useQueryClient, type QueryClient } from '@tanstack/react-query'

const prefetchedKeys = new Set<string>()
const HOVER_INTENT_DELAY_MS = 75

export interface PrefetchIntentHandlers {
  onPointerEnter: () => void
  onPointerLeave: () => void
  onFocus: () => void
  onTouchStart: () => void
}

function runPrefetchOnce(
  key: string,
  queryClient: QueryClient,
  prefetch: (queryClient: QueryClient) => void,
): void {
  if (prefetchedKeys.has(key)) {
    return
  }

  prefetchedKeys.add(key)
  prefetch(queryClient)
}

export function usePrefetchOnIntent(
  key: string,
  prefetch: (queryClient: QueryClient) => void,
): PrefetchIntentHandlers {
  const queryClient = useQueryClient()
  const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null)

  useEffect(
    () => () => {
      if (timeoutRef.current !== null) {
        clearTimeout(timeoutRef.current)
      }
    },
    [],
  )

  return {
    onPointerEnter() {
      if (prefetchedKeys.has(key) || timeoutRef.current !== null) {
        return
      }

      timeoutRef.current = setTimeout(() => {
        timeoutRef.current = null
        runPrefetchOnce(key, queryClient, prefetch)
      }, HOVER_INTENT_DELAY_MS)
    },
    onPointerLeave() {
      if (timeoutRef.current !== null) {
        clearTimeout(timeoutRef.current)
        timeoutRef.current = null
      }
    },
    onFocus() {
      runPrefetchOnce(key, queryClient, prefetch)
    },
    onTouchStart() {
      runPrefetchOnce(key, queryClient, prefetch)
    },
  }
}
