import { useCallback, useEffect, useRef, useState } from 'react'
import type { ContentEntry, ListQuery } from '@platform-modules/content'
import type { ContentClient } from './client.js'
import { stableSerializeQuery } from './stableSerialize.js'

export function useContentList(client: ContentClient, query?: ListQuery) {
  const [entries, setEntries] = useState<ContentEntry[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<Error | null>(null)
  const [reloadToken, setReloadToken] = useState(0)

  const queryKey = stableSerializeQuery(query)
  const clientRef = useRef(client)
  clientRef.current = client
  const queryRef = useRef(query)
  queryRef.current = query

  const reload = useCallback(() => {
    setReloadToken((t) => t + 1)
  }, [])

  useEffect(() => {
    let cancelled = false
    setLoading(true)
    setError(null)

    void clientRef.current
      .list(queryRef.current)
      .then((rows) => {
        if (!cancelled) {
          setEntries(rows)
          setLoading(false)
        }
      })
      .catch((e: unknown) => {
        if (!cancelled) {
          setError(e instanceof Error ? e : new Error(String(e)))
          setLoading(false)
        }
      })

    return () => {
      cancelled = true
    }
  }, [queryKey, reloadToken])

  return { entries, loading, error, reload }
}
