/**
 * Suggestion Badges Component
 *
 * Displays AI-suggested options inline for categories, themes, and colors.
 * Shows similarity scores and allows one-click selection.
 */

import { Sparkles, Loader2, Plus, Check } from 'lucide-react';
import { cn } from '@/lib/utils';
import type { TaxonomySuggestion } from '../store/types';

interface SuggestionBadgesProps {
  /** Suggestions to display */
  suggestions: TaxonomySuggestion[];
  /** Currently selected values (IDs) */
  selectedValues: (string | number)[];
  /** Callback when a suggestion is clicked */
  onSelect: (id: number) => void;
  /** Whether suggestions are loading */
  isLoading?: boolean;
  /** Maximum suggestions to show */
  maxSuggestions?: number;
  /** Minimum similarity to show (0-1) */
  minSimilarity?: number;
  /** Label for the section */
  label?: string;
  /** Compact mode for smaller displays */
  compact?: boolean;
  /** Show similarity scores */
  showScores?: boolean;
  /** Custom class name */
  className?: string;
}

export function SuggestionBadges({
  suggestions,
  selectedValues,
  onSelect,
  isLoading = false,
  maxSuggestions = 5,
  minSimilarity = 0,
  label = 'Suggested',
  compact = false,
  showScores = true,
  className,
}: SuggestionBadgesProps) {
  // Filter and limit suggestions
  const filteredSuggestions = suggestions
    .filter(s => s.similarity >= minSimilarity)
    .slice(0, maxSuggestions);

  // Don't render if no suggestions and not loading
  if (!isLoading && filteredSuggestions.length === 0) {
    return null;
  }

  const isSelected = (id: number) => {
    return selectedValues.some(v => String(v) === String(id));
  };

  return (
    <div className={cn('flex flex-wrap items-center gap-1.5', className)}>
      {/* Label */}
      <div className={cn(
        'flex items-center gap-1 text-purple-600 dark:text-purple-400',
        compact ? 'text-[10px]' : 'text-xs'
      )}>
        <Sparkles className={compact ? 'h-2.5 w-2.5' : 'h-3 w-3'} />
        {!compact && <span className="font-medium">{label}:</span>}
      </div>

      {/* Loading state */}
      {isLoading && (
        <div className="flex items-center gap-1 text-gray-400">
          <Loader2 className={cn('animate-spin', compact ? 'h-2.5 w-2.5' : 'h-3 w-3')} />
          {!compact && <span className="text-xs">Loading...</span>}
        </div>
      )}

      {/* Suggestion badges */}
      {filteredSuggestions.map((suggestion) => {
        const selected = isSelected(suggestion.id);
        const similarityPercent = Math.round(suggestion.similarity * 100);

        return (
          <button
            key={suggestion.id}
            type="button"
            onClick={() => onSelect(suggestion.id)}
            disabled={selected}
            className={cn(
              'inline-flex items-center gap-1 rounded-full border transition-colors',
              compact ? 'px-1.5 py-0.5 text-[10px]' : 'px-2 py-0.5 text-xs',
              selected
                ? 'border-green-300 bg-green-50 text-green-700 dark:border-green-700 dark:bg-green-950 dark:text-green-400'
                : 'border-purple-200 bg-purple-50 text-purple-700 hover:bg-purple-100 dark:border-purple-800 dark:bg-purple-950/50 dark:text-purple-300 dark:hover:bg-purple-900/50'
            )}
            title={suggestion.fullPath || suggestion.name}
          >
            {selected ? (
              <Check className={compact ? 'h-2 w-2' : 'h-2.5 w-2.5'} />
            ) : (
              <Plus className={compact ? 'h-2 w-2' : 'h-2.5 w-2.5'} />
            )}
            <span className="truncate max-w-[120px]">{suggestion.name}</span>
            {showScores && !compact && (
              <span className={cn(
                'opacity-60',
                selected ? 'text-green-600' : 'text-purple-500'
              )}>
                {similarityPercent}%
              </span>
            )}
          </button>
        );
      })}
    </div>
  );
}

/**
 * Inline suggestion for a single field (used inside dropdowns)
 */
interface InlineSuggestionProps {
  suggestion: TaxonomySuggestion;
  isSelected: boolean;
  onSelect: () => void;
  showScore?: boolean;
}

export function InlineSuggestion({
  suggestion,
  isSelected,
  onSelect,
  showScore = true,
}: InlineSuggestionProps) {
  const similarityPercent = Math.round(suggestion.similarity * 100);

  return (
    <div
      className={cn(
        'flex items-center justify-between px-2 py-1.5 cursor-pointer',
        isSelected
          ? 'bg-green-50 dark:bg-green-950/30'
          : 'bg-purple-50/50 hover:bg-purple-100/50 dark:bg-purple-950/20 dark:hover:bg-purple-900/30'
      )}
      onClick={onSelect}
    >
      <div className="flex items-center gap-2 min-w-0">
        <Sparkles className="h-3 w-3 text-purple-500 flex-shrink-0" />
        <span className="truncate text-sm">
          {suggestion.fullPath || suggestion.name}
        </span>
      </div>
      <div className="flex items-center gap-2 flex-shrink-0 ml-2">
        {showScore && (
          <span className="text-xs text-purple-500 dark:text-purple-400">
            {similarityPercent}%
          </span>
        )}
        {isSelected ? (
          <Check className="h-3.5 w-3.5 text-green-500" />
        ) : (
          <Plus className="h-3.5 w-3.5 text-purple-400" />
        )}
      </div>
    </div>
  );
}

/**
 * Suggestion section header for dropdowns
 */
interface SuggestionSectionHeaderProps {
  isLoading?: boolean;
  count?: number;
}

export function SuggestionSectionHeader({ isLoading, count }: SuggestionSectionHeaderProps) {
  return (
    <div className="flex items-center gap-2 px-2 py-1.5 text-xs font-medium text-purple-600 dark:text-purple-400 bg-purple-50/80 dark:bg-purple-950/40 border-b border-purple-100 dark:border-purple-900">
      <Sparkles className="h-3 w-3" />
      <span>AI Suggested</span>
      {isLoading && <Loader2 className="h-3 w-3 animate-spin" />}
      {!isLoading && count !== undefined && (
        <span className="text-purple-400 dark:text-purple-500">({count})</span>
      )}
    </div>
  );
}

export default SuggestionBadges;
