'use client';

import { useState, useEffect } from 'react';
import { tagApi } from '../../lib/api';
import Button from '../ui/Button';
import LoadingSpinner from '../ui/LoadingSpinner';

interface TagSuggestion {
  tagName: string;
  confidence: number;
  reason: string;
}

interface TagSuggestionsProps {
  title: string;
  content?: string;
  summary?: string;
  currentTags: string[];
  onAddTag: (tagName: string) => void;
  disabled?: boolean;
}

export default function TagSuggestions({ 
  title, 
  content, 
  summary, 
  currentTags, 
  onAddTag, 
  disabled = false 
}: TagSuggestionsProps) {
  const [suggestions, setSuggestions] = useState<TagSuggestion[]>([]);
  const [loading, setLoading] = useState(false);
  const [lastAnalyzed, setLastAnalyzed] = useState<string>('');

  useEffect(() => {
    const analyzeContent = async () => {
      // Only analyze if we have meaningful content and it has changed
      const contentKey = `${title}|${summary}`;
      if (!title.trim() || contentKey === lastAnalyzed || disabled) {
        return;
      }

      setLoading(true);
      try {
        const tagSuggestions = await tagApi.suggestTags(title, content, summary, 8);
        
        // Filter out suggestions that are already selected
        const filteredSuggestions = tagSuggestions.filter(
          suggestion => !currentTags.some(tag => 
            tag.toLowerCase() === suggestion.tagName.toLowerCase()
          )
        );
        
        setSuggestions(filteredSuggestions);
        setLastAnalyzed(contentKey);
      } catch (error) {
        console.error('Failed to get tag suggestions:', error);
        setSuggestions([]);
      } finally {
        setLoading(false);
      }
    };

    // Debounce the analysis
    const debounce = setTimeout(analyzeContent, 1000);
    return () => clearTimeout(debounce);
  }, [title, content, summary, currentTags, lastAnalyzed, disabled]);

  const handleAddTag = (tagName: string) => {
    onAddTag(tagName);
    // Remove the added tag from suggestions
    setSuggestions(prev => prev.filter(s => s.tagName !== tagName));
  };

  const getConfidenceColor = (confidence: number) => {
    if (confidence >= 0.7) return 'text-green-600 dark:text-green-400';
    if (confidence >= 0.5) return 'text-yellow-600 dark:text-yellow-400';
    return 'text-gray-600 dark:text-gray-400';
  };

  const getConfidenceLabel = (confidence: number) => {
    if (confidence >= 0.7) return 'High';
    if (confidence >= 0.5) return 'Medium';
    return 'Low';
  };

  if (disabled || (!title.trim() && !summary?.trim())) {
    return null;
  }

  return (
    <div className="mt-4">
      <div className="flex items-center gap-2 mb-3">
        <h3 className="text-sm font-medium theme-text">Suggested Tags</h3>
        {loading && <LoadingSpinner size="sm" />}
      </div>
      
      {suggestions.length === 0 && !loading ? (
        <p className="text-sm theme-text-muted">
          {title.trim() ? 'No tag suggestions found for this content' : 'Enter a title to get tag suggestions'}
        </p>
      ) : (
        <div className="space-y-2">
          {suggestions.map((suggestion) => (
            <div
              key={suggestion.tagName}
              className="flex items-center justify-between p-3 border theme-border rounded-lg hover:bg-gray-50 dark:hover:bg-gray-800/50 transition-colors"
            >
              <div className="flex-1 min-w-0">
                <div className="flex items-center gap-2">
                  <span className="font-medium theme-text">{suggestion.tagName}</span>
                  <span className={`text-xs px-2 py-1 rounded-full border ${getConfidenceColor(suggestion.confidence)}`}>
                    {getConfidenceLabel(suggestion.confidence)}
                  </span>
                </div>
                <p className="text-xs theme-text-muted mt-1">{suggestion.reason}</p>
              </div>
              <Button
                variant="secondary"
                size="sm"
                onClick={() => handleAddTag(suggestion.tagName)}
                className="ml-3"
              >
                Add
              </Button>
            </div>
          ))}
        </div>
      )}
      
      {suggestions.length > 0 && (
        <div className="mt-3 flex justify-center">
          <Button
            variant="ghost"
            size="sm"
            onClick={() => {
              suggestions.forEach(s => handleAddTag(s.tagName));
            }}
          >
            Add All Suggestions
          </Button>
        </div>
      )}
    </div>
  );
}