import { useState, useEffect } from 'react'
import { useSearchParams } from 'next/navigation'
import { useSession } from 'next-auth/react'

/**
 * Hook to check if auto label suggestions should be shown for the current notebook
 * Triggers when notebook has 15+ notes (IA4)
 */
export function useAutoLabelSuggestion() {
  const { data: session } = useSession()
  const searchParams = useSearchParams()
  const [shouldSuggest, setShouldSuggest] = useState(false)
  const [notebookId, setNotebookId] = useState<string | null>(searchParams.get('notebook'))
  const [hasChecked, setHasChecked] = useState(false)

  useEffect(() => {
    const currentNotebookId = searchParams.get('notebook')

    // Reset when notebook changes
    if (currentNotebookId !== notebookId) {
      setNotebookId(currentNotebookId)
      setHasChecked(false)
      setShouldSuggest(false)

      // Check if we should suggest labels for this notebook
      if (currentNotebookId && session?.user?.id) {
        checkNotebookForSuggestions(currentNotebookId)
      }
    }
  }, [searchParams, notebookId, session])

  const checkNotebookForSuggestions = async (nbId: string) => {
    try {
      // Check if notebook has 15+ notes
      const response = await fetch('/api/ai/auto-labels', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify({ notebookId: nbId }),
      })

      const data = await response.json()

      // Show suggestions if available
      if (data.success && data.data) {
        setShouldSuggest(true)
      }

      setHasChecked(true)
    } catch (error) {
      console.error('Failed to check for label suggestions:', error)
      setHasChecked(true)
    }
  }

  return {
    shouldSuggest,
    notebookId,
    hasChecked,
    dismiss: () => setShouldSuggest(false),
  }
}
