'use client';

import { Tag } from '../../types/api';

interface TagFilterProps {
  tags: Tag[];
  selectedTags: string[];
  onTagToggle: (tagName: string) => void;
  showCollectionCount?: boolean;
}

export default function TagFilter({ tags, selectedTags, onTagToggle, showCollectionCount = false }: TagFilterProps) {
  if (!Array.isArray(tags) || tags.length === 0) return null;

  // Filter out tags with no count, then sort by usage count (descending) and then alphabetically
  const sortedTags = [...tags]
    .filter(tag => {
      const count = showCollectionCount ? (tag.collectionCount || 0) : (tag.storyCount || 0);
      return count > 0;
    })
    .sort((a, b) => {
      const aCount = showCollectionCount ? (a.collectionCount || 0) : (a.storyCount || 0);
      const bCount = showCollectionCount ? (b.collectionCount || 0) : (b.storyCount || 0);
      if (bCount !== aCount) {
        return bCount - aCount;
      }
      return a.name.localeCompare(b.name);
    });

  return (
    <div className="space-y-2">
      <h3 className="text-sm font-medium theme-header">Filter by Tags:</h3>
      <div className="flex flex-wrap gap-2 max-h-32 overflow-y-auto">
        {sortedTags.map((tag) => {
          const isSelected = selectedTags.includes(tag.name);
          
          return (
            <button
              key={tag.id}
              onClick={() => onTagToggle(tag.name)}
              className={`px-3 py-1 text-sm rounded-full border transition-colors ${
                isSelected
                  ? 'theme-accent-bg text-white border-transparent'
                  : 'theme-card theme-text theme-border hover:border-gray-400'
              }`}
            >
              {tag.name} ({showCollectionCount ? (tag.collectionCount || 0) : (tag.storyCount || 0)})
            </button>
          );
        })}
      </div>
      
      {selectedTags.length > 0 && (
        <div className="text-sm theme-text">
          Filtering by: {selectedTags.join(', ')}
        </div>
      )}
    </div>
  );
}