import { useState, useEffect } from 'react'
import { useDebounce } from './use-debounce'

export interface TitleSuggestion {
  title: string
  confidence: number
  reasoning?: string
}

interface UseTitleSuggestionsProps {
  content: string
  enabled?: boolean
}

export function useTitleSuggestions({ content, enabled = true }: UseTitleSuggestionsProps) {
  const [suggestions, setSuggestions] = useState<TitleSuggestion[]>([])
  const [isAnalyzing, setIsAnalyzing] = useState(false)
  const [error, setError] = useState<string | null>(null)

  // Debounce le contenu de 2s pour éviter trop d'appels
  const debouncedContent = useDebounce(content, 2000)

  useEffect(() => {
    if (!enabled || !debouncedContent) {
      setSuggestions([])
      return
    }

    const wordCount = debouncedContent.split(/\s+/).length

    // Il faut au moins 10 mots
    if (wordCount < 10) {
      setSuggestions([])
      return
    }


    const generateTitles = async () => {
      setIsAnalyzing(true)
      setError(null)

      try {
        const response = await fetch('/api/ai/title-suggestions', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ content: debouncedContent }),
        })


        if (!response.ok) {
          const errorData = await response.json()
          throw new Error(errorData.error || 'Erreur lors de la génération des titres')
        }

        const data = await response.json()
        setSuggestions(data.suggestions || [])
      } catch (err) {
        console.error('❌ Title suggestions error:', err)
        setError('Impossible de générer des suggestions de titres')
      } finally {
        setIsAnalyzing(false)
      }
    }

    generateTitles()
  }, [debouncedContent, enabled])

  return {
    suggestions,
    isAnalyzing,
    error,
    clearSuggestions: () => setSuggestions([])
  }
}
