import { useLanguage } from '@/lib/i18n'
import { useState, useEffect, useRef } from 'react';
import { useDebounce } from './use-debounce';
import { TagSuggestion } from '@/lib/ai/types';

interface UseAutoTaggingProps {
  content: string;
  notebookId?: string | null;
  enabled?: boolean;
}

export function useAutoTagging({ content, notebookId, enabled = true }: UseAutoTaggingProps) {
  const { language } = useLanguage();
  const [suggestions, setSuggestions] = useState<TagSuggestion[]>([]);
  const [isAnalyzing, setIsAnalyzing] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // Debounce le contenu de 1.5s
  const debouncedContent = useDebounce(content, 1500);

  // Track previous notebookId to detect when note is moved to a notebook
  const previousNotebookId = useRef<string | null | undefined>(notebookId);

  const analyzeContent = async (contentToAnalyze: string) => {
    // CRITICAL: Don't suggest labels in "Notes générales" (notebookId is null)
    // Labels should ONLY appear within notebooks, not in the general notes section
    if (!notebookId) {
      setSuggestions([]);
      return;
    }

    if (!contentToAnalyze || contentToAnalyze.length < 10) {
      setSuggestions([]);
      return;
    }

    setIsAnalyzing(true);
    setError(null);

    try {
      const response = await fetch('/api/ai/tags', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          content: contentToAnalyze,
          notebookId: notebookId || undefined,
          language: language || document.documentElement.lang || 'en',
        }),
      });

      if (!response.ok) {
        throw new Error('Erreur lors de l\'analyse');
      }

      const data = await response.json();
      setSuggestions(data.tags || []);
    } catch (err) {
      setError('Impossible de générer des suggestions');
    } finally {
      setIsAnalyzing(false);
    }
  };

  // Trigger on content change
  useEffect(() => {
    if (!enabled) {
      setSuggestions([]);
      return;
    }

    analyzeContent(debouncedContent);
  }, [debouncedContent, enabled]);

  // CRITICAL: Also trigger when notebookId changes from null/undefined to a value (note moved to notebook)
  useEffect(() => {
    if (!enabled) return;

    const prev = previousNotebookId.current;
    previousNotebookId.current = notebookId;

    // Detect when note is moved FROM "Notes générales" (null) TO a notebook
    const wasMovedToNotebook = (prev === null || prev === undefined) && notebookId;

    if (wasMovedToNotebook && content && content.length >= 10) {
      // Use current content immediately (no debounce) when moving to notebook
      analyzeContent(content);
    }
  }, [notebookId, content, enabled]);

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