import { useState, useCallback } from 'react'
import type { ChunkDetail, TraceabilityResult } from './types'
import { API_PROXY } from './types'

export function useQualitySearch() {
  const [searchQuery, setSearchQuery] = useState('')
  const [searchResults, setSearchResults] = useState<ChunkDetail[]>([])
  const [searching, setSearching] = useState(false)
  const [selectedRegulation, setSelectedRegulation] = useState<string>('')
  const [topK, setTopK] = useState(10)

  const [selectedChunk, setSelectedChunk] = useState<ChunkDetail | null>(null)
  const [traceability, setTraceability] = useState<TraceabilityResult | null>(null)
  const [loadingTrace, setLoadingTrace] = useState(false)

  const handleSearch = useCallback(async () => {
    if (!searchQuery.trim()) return

    setSearching(true)
    setSearchResults([])
    setSelectedChunk(null)
    setTraceability(null)

    try {
      let url = `${API_PROXY}?action=search&query=${encodeURIComponent(searchQuery)}&top_k=${topK}`
      if (selectedRegulation) {
        url += `&regulations=${encodeURIComponent(selectedRegulation)}`
      }

      const res = await fetch(url)
      if (res.ok) {
        const data = await res.json()
        setSearchResults(data.results || [])
      }
    } catch (error) {
      console.error('Search failed:', error)
    } finally {
      setSearching(false)
    }
  }, [searchQuery, selectedRegulation, topK])

  const loadTraceability = useCallback(async (chunk: ChunkDetail) => {
    setSelectedChunk(chunk)
    setLoadingTrace(true)

    try {
      const res = await fetch(
        `${API_PROXY}?action=traceability&chunk_id=${encodeURIComponent(chunk.id || chunk.regulation_code + '_' + chunk.chunk_index)}&regulation=${encodeURIComponent(chunk.regulation_code)}`
      )

      if (res.ok) {
        const data = await res.json()
        setTraceability({
          chunk,
          requirements: data.requirements || [],
          controls: data.controls || [],
        })
      } else {
        setTraceability({ chunk, requirements: [], controls: [] })
      }
    } catch (error) {
      console.error('Failed to load traceability:', error)
      setTraceability({ chunk, requirements: [], controls: [] })
    } finally {
      setLoadingTrace(false)
    }
  }, [])

  const handleSampleQuery = (query: string, reg: string) => {
    setSearchQuery(query)
    setSelectedRegulation(reg)
    setTimeout(() => {
      handleSearch()
    }, 100)
  }

  return {
    searchQuery,
    setSearchQuery,
    searchResults,
    searching,
    selectedRegulation,
    setSelectedRegulation,
    topK,
    setTopK,
    selectedChunk,
    traceability,
    loadingTrace,
    handleSearch,
    loadTraceability,
    handleSampleQuery,
  }
}
