'use client'

import { useState } from 'react'
import { useSDK } from '@/lib/sdk'
import { RAGControlSuggestion } from '../_types'

export function useRAGSuggestions(setError: (e: string | null) => void) {
  const { dispatch } = useSDK()
  const [ragLoading, setRagLoading] = useState(false)
  const [ragSuggestions, setRagSuggestions] = useState<RAGControlSuggestion[]>([])
  const [showRagPanel, setShowRagPanel] = useState(false)
  const [selectedRequirementId, setSelectedRequirementId] = useState<string>('')

  const suggestControlsFromRAG = async () => {
    if (!selectedRequirementId) {
      setError('Bitte eine Anforderungs-ID eingeben.')
      return
    }
    setRagLoading(true)
    setRagSuggestions([])
    try {
      const res = await fetch('/api/sdk/v1/compliance/ai/suggest-controls', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ requirement_id: selectedRequirementId }),
      })
      if (!res.ok) {
        const msg = await res.text()
        throw new Error(msg || `HTTP ${res.status}`)
      }
      const data = await res.json()
      setRagSuggestions(data.suggestions || [])
      setShowRagPanel(true)
    } catch (e) {
      setError(`KI-Vorschläge fehlgeschlagen: ${e instanceof Error ? e.message : 'Unbekannter Fehler'}`)
    } finally {
      setRagLoading(false)
    }
  }

  const addSuggestedControl = (suggestion: RAGControlSuggestion) => {
    const newControl: import('@/lib/sdk').Control = {
      id: `rag-${suggestion.control_id}-${Date.now()}`,
      name: suggestion.title,
      description: suggestion.description,
      type: 'TECHNICAL',
      category: suggestion.domain,
      implementationStatus: 'NOT_IMPLEMENTED',
      effectiveness: 'LOW',
      evidence: [],
      owner: null,
      dueDate: null,
    }
    dispatch({ type: 'ADD_CONTROL', payload: newControl })
    setRagSuggestions(prev => prev.filter(s => s.control_id !== suggestion.control_id))
  }

  return {
    ragLoading,
    ragSuggestions,
    showRagPanel,
    setShowRagPanel,
    selectedRequirementId,
    setSelectedRequirementId,
    suggestControlsFromRAG,
    addSuggestedControl,
  }
}
