import { useCallback, useEffect, useRef, useState } from 'react'

import type { Document, DocumentStatus } from '../../lib/types'
import { listDocuments } from './api'

const ACTIVE = new Set<DocumentStatus>(['pending', 'indexing', 'deleting'])

export function useDocuments(filter?: DocumentStatus) {
  const [documents, setDocuments] = useState<Document[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const mounted = useRef(true)

  const refresh = useCallback(async () => {
    try {
      const page = await listDocuments(filter)
      if (mounted.current) {
        setDocuments(page.items)
        setError(null)
      }
    } catch (reason) {
      if (mounted.current) setError(reason instanceof Error ? reason.message : '文档加载失败')
    } finally {
      if (mounted.current) setLoading(false)
    }
  }, [filter])

  useEffect(() => {
    mounted.current = true
    listDocuments(filter)
      .then((page) => {
        if (!mounted.current) return
        setDocuments(page.items)
        setError(null)
      })
      .catch((reason) => {
        if (mounted.current) setError(reason instanceof Error ? reason.message : '文档加载失败')
      })
      .finally(() => {
        if (mounted.current) setLoading(false)
      })
    return () => { mounted.current = false }
  }, [filter])

  useEffect(() => {
    if (!documents.some((document) => ACTIVE.has(document.status))) return
    const timer = window.setInterval(() => void refresh(), 2_000)
    return () => window.clearInterval(timer)
  }, [documents, refresh])

  return { documents, loading, error, refresh }
}
