import {useEffect, useState} from 'react'

import {cleanError, unwrap} from '@/lib/errors'
import {rpc} from '@/lib/rpc'
import {type PublicProfile} from '@/stores/friends'

const DEBOUNCE_MS = 300

// server-side handle search over the viewer's friends; results are null
// while the query is empty so the caller can fall back to the paged
// friends list. loading/error derive from whether the settled response
// matches the live query, so no state is set synchronously
export const useFriendSearch = (query: string) => {
  const q = query.trim()
  const [settled, setSettled] = useState<{
    q: string
    results: PublicProfile[] | null
    error: string | null
  }>({q: '', results: null, error: null})

  useEffect(() => {
    if (!q) return
    let cancelled = false
    const timer = setTimeout(async () => {
      try {
        const {friends} = await unwrap(rpc.friends.$get({query: {q}}))
        if (!cancelled) setSettled({q, results: friends, error: null})
      } catch (err) {
        if (!cancelled)
          setSettled({q, results: null, error: cleanError(err)})
      }
    }, DEBOUNCE_MS)
    return () => {
      cancelled = true
      clearTimeout(timer)
    }
  }, [q])

  if (!q) return {results: null, loading: false, error: null}
  const current = settled.q === q
  return {
    // keep prior results visible while a fresh query is in flight
    results: settled.results,
    loading: !current,
    error: current ? settled.error : null,
  }
}
