import { useEffect, useRef, useState } from 'react'
import { Message } from '@arco-design/web-react'
import type { ApiSession } from '../api/client'
import { searchWorkspace, type SearchResultDTO } from '../api/search'
import { createSearchRequestGate, type SearchRequestGate } from './search-request-gate'

export function useWorkbenchSearch(session: ApiSession | null) {
  const [query, setQuery] = useState('')
  const [results, setResults] = useState<SearchResultDTO[]>([])
  const [loading, setLoading] = useState(false)
  const [searched, setSearched] = useState(false)
  const requestGate = useRef<SearchRequestGate | null>(null)
  if (!requestGate.current) requestGate.current = createSearchRequestGate()

  useEffect(() => {
    const gate = requestGate.current
    gate?.invalidate()
    setQuery('')
    setResults([])
    setLoading(false)
    setSearched(false)
    return () => gate?.invalidate()
  }, [session])

  function changeQuery(value: string) {
    requestGate.current?.invalidate()
    setQuery(value)
    setLoading(false)
    setSearched(false)
  }

  async function submitSearch() {
    const trimmedQuery = query.trim()
    if (!trimmedQuery) {
      requestGate.current?.invalidate()
      setResults([])
      setSearched(false)
      Message.warning('请输入搜索关键词')
      return
    }
    if (!session) {
      requestGate.current?.invalidate()
      Message.error('未登录或登录已失效')
      return
    }

    const request = requestGate.current!.begin()
    setLoading(true)
    setSearched(false)
    try {
      const response = await searchWorkspace(session, trimmedQuery, request.signal)
      if (!request.isCurrent()) return
      setResults(response.items)
      setSearched(true)
    } catch (error) {
      if (!request.isCurrent()) return
      setResults([])
      Message.error(error instanceof Error ? error.message : '搜索失败，请稍后重试')
    } finally {
      if (request.isCurrent()) setLoading(false)
    }
  }

  return {
    query,
    results,
    loading,
    searched,
    onQueryChange: changeQuery,
    onSearch: submitSearch,
  }
}
