'use client';

import { useState, useEffect } from 'react';
import AppLayout from '../../../components/layout/AppLayout';
import { tagApi } from '../../../lib/api';
import { Tag } from '../../../types/api';
import Button from '../../../components/ui/Button';
import { Input } from '../../../components/ui/Input';
import LoadingSpinner from '../../../components/ui/LoadingSpinner';
import TagDisplay from '../../../components/tags/TagDisplay';
import TagEditModal from '../../../components/tags/TagEditModal';

export default function TagMaintenancePage() {
  const [tags, setTags] = useState<Tag[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState('');
  const [sortBy, setSortBy] = useState<'name' | 'storyCount' | 'createdAt'>('name');
  const [sortDirection, setSortDirection] = useState<'asc' | 'desc'>('asc');
  const [selectedTag, setSelectedTag] = useState<Tag | null>(null);
  const [isEditModalOpen, setIsEditModalOpen] = useState(false);
  const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);
  const [selectedTagIds, setSelectedTagIds] = useState<Set<string>>(new Set());
  const [isMergeModalOpen, setIsMergeModalOpen] = useState(false);
  const [mergeTargetTagId, setMergeTargetTagId] = useState<string>('');
  const [mergePreview, setMergePreview] = useState<any>(null);
  const [merging, setMerging] = useState(false);
  const [isMergeSuggestionsModalOpen, setIsMergeSuggestionsModalOpen] = useState(false);
  const [mergeSuggestions, setMergeSuggestions] = useState<Array<{
    group: Tag[];
    similarity: number;
    reason: string;
  }>>([]);

  useEffect(() => {
    loadTags();
  }, []);

  const loadTags = async () => {
    try {
      setLoading(true);
      const result = await tagApi.getTags({
        page: 0,
        size: 1000, // Load all tags for maintenance
        sortBy,
        sortDir: sortDirection
      });
      setTags(result.content || []);
    } catch (error) {
      console.error('Failed to load tags:', error);
      setTags([]);
    } finally {
      setLoading(false);
    }
  };

  const handleTagSave = (updatedTag: Tag) => {
    if (selectedTag) {
      // Update existing tag
      setTags(prev => prev.map(tag => 
        tag.id === updatedTag.id ? updatedTag : tag
      ));
    } else {
      // Add new tag
      setTags(prev => [...prev, updatedTag]);
    }
    setSelectedTag(null);
    setIsEditModalOpen(false);
    setIsCreateModalOpen(false);
  };

  const handleTagDelete = (deletedTag: Tag) => {
    setTags(prev => prev.filter(tag => tag.id !== deletedTag.id));
    setSelectedTag(null);
    setIsEditModalOpen(false);
  };

  const handleEditTag = (tag: Tag) => {
    setSelectedTag(tag);
    setIsEditModalOpen(true);
  };

  const handleCreateTag = () => {
    setSelectedTag(null);
    setIsCreateModalOpen(true);
  };

  const handleSortChange = (newSortBy: typeof sortBy) => {
    if (newSortBy === sortBy) {
      setSortDirection(prev => prev === 'asc' ? 'desc' : 'asc');
    } else {
      setSortBy(newSortBy);
      setSortDirection('asc');
    }
  };

  const handleTagSelection = (tagId: string, selected: boolean) => {
    setSelectedTagIds(prev => {
      const newSet = new Set(prev);
      if (selected) {
        newSet.add(tagId);
      } else {
        newSet.delete(tagId);
      }
      return newSet;
    });
  };

  const handleSelectAll = (selected: boolean) => {
    if (selected) {
      setSelectedTagIds(new Set(filteredTags.map(tag => tag.id)));
    } else {
      setSelectedTagIds(new Set());
    }
  };

  const handleSelectUnused = () => {
    const unusedTags = filteredTags.filter(tag => !tag.storyCount || tag.storyCount === 0);
    setSelectedTagIds(new Set(unusedTags.map(tag => tag.id)));
  };

  const handleDeleteSelected = async () => {
    if (selectedTagIds.size === 0) return;

    const confirmation = confirm(
      `Are you sure you want to delete ${selectedTagIds.size} selected tag(s)? This action cannot be undone.`
    );

    if (!confirmation) return;

    try {
      const deletePromises = Array.from(selectedTagIds).map(tagId =>
        tagApi.deleteTag(tagId)
      );

      await Promise.all(deletePromises);

      // Reload tags and reset selection
      await loadTags();
      setSelectedTagIds(new Set());
    } catch (error: any) {
      console.error('Failed to delete tags:', error);
      const errorMessage = error.response?.data?.error || error.message || 'Failed to delete some tags. Please try again.';
      alert(errorMessage);
    }
  };

  const generateMergeSuggestions = () => {
    const suggestions: Array<{
      group: Tag[];
      similarity: number;
      reason: string;
    }> = [];

    // Helper function to calculate similarity between two strings
    const calculateSimilarity = (str1: string, str2: string): number => {
      const s1 = str1.toLowerCase();
      const s2 = str2.toLowerCase();
      
      // Exact match
      if (s1 === s2) return 1.0;
      
      // Check for common patterns
      const patterns = [
        // Plural vs singular
        { regex: /(.+)s$/, match: (a: string, b: string) => a === b + 's' || b === a + 's' },
        // Hyphen vs underscore vs space
        { regex: /[-_\s]/, match: (a: string, b: string) => 
          a.replace(/[-_\s]/g, '') === b.replace(/[-_\s]/g, '') },
        // Common abbreviations
        { regex: /\b(and|&)\b/, match: (a: string, b: string) => 
          a.replace(/\band\b/g, '&') === b || a === b.replace(/\band\b/g, '&') },
      ];
      
      for (const pattern of patterns) {
        if (pattern.match(s1, s2)) return 0.9;
      }
      
      // Levenshtein distance for similar words
      const distance = levenshteinDistance(s1, s2);
      const maxLength = Math.max(s1.length, s2.length);
      const similarity = 1 - (distance / maxLength);
      
      return similarity > 0.8 ? similarity : 0;
    };

    // Simple Levenshtein distance implementation
    const levenshteinDistance = (str1: string, str2: string): number => {
      const matrix = Array(str2.length + 1).fill(null).map(() => Array(str1.length + 1).fill(null));
      
      for (let i = 0; i <= str1.length; i++) matrix[0][i] = i;
      for (let j = 0; j <= str2.length; j++) matrix[j][0] = j;
      
      for (let j = 1; j <= str2.length; j++) {
        for (let i = 1; i <= str1.length; i++) {
          const indicator = str1[i - 1] === str2[j - 1] ? 0 : 1;
          matrix[j][i] = Math.min(
            matrix[j][i - 1] + 1,
            matrix[j - 1][i] + 1,
            matrix[j - 1][i - 1] + indicator
          );
        }
      }
      
      return matrix[str2.length][str1.length];
    };

    // Find similar tags
    const processedTags = new Set<string>();
    
    for (let i = 0; i < tags.length; i++) {
      if (processedTags.has(tags[i].id)) continue;
      
      const similarTags = [tags[i]];
      processedTags.add(tags[i].id);
      
      for (let j = i + 1; j < tags.length; j++) {
        if (processedTags.has(tags[j].id)) continue;
        
        const similarity = calculateSimilarity(tags[i].name, tags[j].name);
        if (similarity > 0.8) {
          similarTags.push(tags[j]);
          processedTags.add(tags[j].id);
        }
      }
      
      if (similarTags.length > 1) {
        const maxSimilarity = Math.max(...similarTags.slice(1).map(tag => 
          calculateSimilarity(similarTags[0].name, tag.name)
        ));
        
        let reason = 'Similar names detected';
        if (maxSimilarity === 0.9) {
          reason = 'Likely plural/singular or formatting variations';
        } else if (maxSimilarity > 0.95) {
          reason = 'Very similar names, possible duplicates';
        }
        
        suggestions.push({
          group: similarTags,
          similarity: maxSimilarity,
          reason
        });
      }
    }
    
    // Sort by similarity descending
    suggestions.sort((a, b) => b.similarity - a.similarity);
    
    setMergeSuggestions(suggestions);
    setIsMergeSuggestionsModalOpen(true);
  };

  const handleMergeSelected = () => {
    if (selectedTagIds.size < 2) {
      alert('Please select at least 2 tags to merge');
      return;
    }
    setIsMergeModalOpen(true);
  };

  const handleMergePreview = async () => {
    if (!mergeTargetTagId || selectedTagIds.size < 2) return;
    
    try {
      const sourceTagIds = Array.from(selectedTagIds).filter(id => id !== mergeTargetTagId);
      const preview = await tagApi.previewMerge(sourceTagIds, mergeTargetTagId);
      setMergePreview(preview);
    } catch (error) {
      console.error('Failed to preview merge:', error);
      alert('Failed to preview merge');
    }
  };

  const handleConfirmMerge = async () => {
    if (!mergeTargetTagId || selectedTagIds.size < 2) return;
    
    try {
      setMerging(true);
      const sourceTagIds = Array.from(selectedTagIds).filter(id => id !== mergeTargetTagId);
      await tagApi.mergeTags(sourceTagIds, mergeTargetTagId);
      
      // Reload tags and reset state
      await loadTags();
      setSelectedTagIds(new Set());
      setMergeTargetTagId('');
      setMergePreview(null);
      setIsMergeModalOpen(false);
    } catch (error) {
      console.error('Failed to merge tags:', error);
      alert('Failed to merge tags');
    } finally {
      setMerging(false);
    }
  };

  // Filter and sort tags
  const filteredTags = tags
    .filter(tag => 
      tag.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
      (tag.description && tag.description.toLowerCase().includes(searchQuery.toLowerCase()))
    )
    .sort((a, b) => {
      let aValue, bValue;
      
      switch (sortBy) {
        case 'name':
          aValue = a.name.toLowerCase();
          bValue = b.name.toLowerCase();
          break;
        case 'storyCount':
          aValue = a.storyCount || 0;
          bValue = b.storyCount || 0;
          break;
        case 'createdAt':
          aValue = new Date(a.createdAt || 0).getTime();
          bValue = new Date(b.createdAt || 0).getTime();
          break;
        default:
          return 0;
      }
      
      if (sortDirection === 'asc') {
        return aValue < bValue ? -1 : aValue > bValue ? 1 : 0;
      } else {
        return aValue > bValue ? -1 : aValue < bValue ? 1 : 0;
      }
    });

  const getSortIcon = (column: typeof sortBy) => {
    if (sortBy !== column) return '↕️';
    return sortDirection === 'asc' ? '↑' : '↓';
  };

  const tagStats = {
    total: tags.length,
    withColors: tags.filter(tag => tag.color).length,
    withDescriptions: tags.filter(tag => tag.description).length,
    withAliases: tags.filter(tag => tag.aliasCount && tag.aliasCount > 0).length,
    unused: tags.filter(tag => !tag.storyCount || tag.storyCount === 0).length
  };

  if (loading) {
    return (
      <AppLayout>
        <div className="flex items-center justify-center py-20">
          <LoadingSpinner size="lg" />
        </div>
      </AppLayout>
    );
  }

  return (
    <AppLayout>
      <div className="max-w-6xl mx-auto space-y-6">
        {/* Header */}
        <div className="flex justify-between items-start">
          <div>
            <h1 className="text-3xl font-bold theme-header">Tag Maintenance</h1>
            <p className="theme-text mt-2">
              Manage tag colors, descriptions, and aliases for better organization
            </p>
          </div>
          <div className="flex gap-3">
            <Button href="/settings" variant="ghost">
              ← Back to Settings
            </Button>
            <Button onClick={handleCreateTag} variant="primary">
              + Create Tag
            </Button>
          </div>
        </div>

        {/* Statistics */}
        <div className="theme-card theme-shadow rounded-lg p-6">
          <h2 className="text-lg font-semibold theme-header mb-4">Tag Statistics</h2>
          <div className="grid grid-cols-2 md:grid-cols-5 gap-4 text-center">
            <div>
              <div className="text-2xl font-bold theme-accent">{tagStats.total}</div>
              <div className="text-sm theme-text">Total Tags</div>
            </div>
            <div>
              <div className="text-2xl font-bold text-blue-600">{tagStats.withColors}</div>
              <div className="text-sm theme-text">With Colors</div>
            </div>
            <div>
              <div className="text-2xl font-bold text-green-600">{tagStats.withDescriptions}</div>
              <div className="text-sm theme-text">With Descriptions</div>
            </div>
            <div>
              <div className="text-2xl font-bold text-purple-600">{tagStats.withAliases}</div>
              <div className="text-sm theme-text">With Aliases</div>
            </div>
            <div>
              <div className="text-2xl font-bold text-gray-500">{tagStats.unused}</div>
              <div className="text-sm theme-text">Unused</div>
            </div>
          </div>
        </div>

        {/* Controls */}
        <div className="theme-card theme-shadow rounded-lg p-6">
          <div className="flex flex-col md:flex-row gap-4 items-center">
            <div className="flex-1">
              <Input
                type="search"
                placeholder="Search tags by name or description..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="w-full"
              />
            </div>
            <div className="flex gap-2">
              <button
                onClick={() => handleSortChange('name')}
                className="px-3 py-2 text-sm border theme-border rounded-lg theme-card theme-text hover:theme-accent transition-colors"
              >
                Name {getSortIcon('name')}
              </button>
              <button
                onClick={() => handleSortChange('storyCount')}
                className="px-3 py-2 text-sm border theme-border rounded-lg theme-card theme-text hover:theme-accent transition-colors"
              >
                Usage {getSortIcon('storyCount')}
              </button>
              <button
                onClick={() => handleSortChange('createdAt')}
                className="px-3 py-2 text-sm border theme-border rounded-lg theme-card theme-text hover:theme-accent transition-colors"
              >
                Date {getSortIcon('createdAt')}
              </button>
            </div>
          </div>
        </div>

        {/* Tags List */}
        <div className="theme-card theme-shadow rounded-lg p-6">
          <div className="flex justify-between items-center mb-4">
            <h2 className="text-lg font-semibold theme-header">
              Tags ({filteredTags.length})
            </h2>
            <div className="flex gap-2">
              <Button
                variant="secondary"
                size="sm"
                onClick={generateMergeSuggestions}
              >
                🔍 Merge Suggestions
              </Button>
              {selectedTagIds.size > 0 && (
                <>
                  <Button
                    variant="ghost"
                    size="sm"
                    onClick={() => setSelectedTagIds(new Set())}
                  >
                    Clear Selection ({selectedTagIds.size})
                  </Button>
                  <Button
                    variant="danger"
                    size="sm"
                    onClick={handleDeleteSelected}
                  >
                    🗑️ Delete Selected
                  </Button>
                  <Button
                    variant="primary"
                    size="sm"
                    onClick={handleMergeSelected}
                    disabled={selectedTagIds.size < 2}
                  >
                    Merge Selected
                  </Button>
                </>
              )}
            </div>
          </div>
          
          {filteredTags.length > 0 && (
            <div className="mb-4 flex items-center gap-4">
              <div className="flex items-center gap-2">
                <input
                  type="checkbox"
                  checked={filteredTags.length > 0 && selectedTagIds.size === filteredTags.length}
                  onChange={(e) => handleSelectAll(e.target.checked)}
                  className="rounded"
                />
                <label className="text-sm theme-text">Select All</label>
              </div>
              <Button
                variant="ghost"
                size="sm"
                onClick={handleSelectUnused}
                disabled={tagStats.unused === 0}
              >
                Select Unused ({tagStats.unused})
              </Button>
            </div>
          )}
          
          {filteredTags.length === 0 ? (
            <div className="text-center py-12">
              <p className="theme-text text-lg mb-4">
                {searchQuery ? 'No tags match your search.' : 'No tags found.'}
              </p>
              {!searchQuery && (
                <Button onClick={handleCreateTag} variant="primary">
                  Create Your First Tag
                </Button>
              )}
            </div>
          ) : (
            <div className="space-y-3">
              {filteredTags.map((tag) => (
                <div
                  key={tag.id}
                  className="flex items-center justify-between p-4 border theme-border rounded-lg hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors"
                >
                  <div className="flex items-center gap-4 min-w-0 flex-1">
                    <input
                      type="checkbox"
                      checked={selectedTagIds.has(tag.id)}
                      onChange={(e) => handleTagSelection(tag.id, e.target.checked)}
                      className="rounded"
                    />
                    <TagDisplay
                      tag={tag}
                      size="md"
                      showAliasesTooltip={true}
                      clickable={false}
                    />
                    <div className="min-w-0 flex-1">
                      {tag.description && (
                        <p className="text-sm theme-text-muted mt-1 truncate">
                          {tag.description}
                        </p>
                      )}
                      <div className="flex gap-4 text-xs theme-text-muted mt-1">
                        <a 
                          href={`/library?tags=${encodeURIComponent(tag.name)}`}
                          className="hover:theme-accent hover:underline cursor-pointer"
                          title={`View ${tag.storyCount || 0} stories with tag "${tag.name}"`}
                        >
                          {tag.storyCount || 0} stories
                        </a>
                        {tag.aliasCount && tag.aliasCount > 0 && (
                          <span>{tag.aliasCount} aliases</span>
                        )}
                        {tag.createdAt && (
                          <span>Created {new Date(tag.createdAt).toLocaleDateString()}</span>
                        )}
                      </div>
                    </div>
                  </div>
                  <div className="flex gap-2 ml-4">
                    <Button
                      variant="ghost"
                      size="sm"
                      onClick={() => handleEditTag(tag)}
                    >
                      Edit
                    </Button>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>

      {/* Edit Modal */}
      <TagEditModal
        tag={selectedTag || undefined}
        isOpen={isEditModalOpen}
        onClose={() => {
          setIsEditModalOpen(false);
          setSelectedTag(null);
        }}
        onSave={handleTagSave}
        onDelete={handleTagDelete}
      />

      {/* Create Modal */}
      <TagEditModal
        tag={undefined}
        isOpen={isCreateModalOpen}
        onClose={() => setIsCreateModalOpen(false)}
        onSave={handleTagSave}
      />

      {/* Merge Modal */}
      {isMergeModalOpen && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white dark:bg-gray-800 rounded-lg p-6 max-w-2xl w-full mx-4 max-h-[80vh] overflow-y-auto">
            <h2 className="text-2xl font-bold theme-header mb-4">Merge Tags</h2>
            
            <div className="space-y-4">
              <div>
                <p className="theme-text mb-2">
                  You have selected {selectedTagIds.size} tags to merge.
                </p>
                <p className="text-sm theme-text-muted mb-4">
                  Choose which tag should become the canonical name. All other tags will become aliases.
                </p>
              </div>

              {/* Target Tag Selection */}
              <div>
                <label className="block text-sm font-medium theme-text mb-2">
                  Canonical Tag (keep this name):
                </label>
                <select
                  value={mergeTargetTagId}
                  onChange={(e) => {
                    setMergeTargetTagId(e.target.value);
                    setMergePreview(null);
                  }}
                  className="w-full p-2 border theme-border rounded-lg theme-card theme-text"
                >
                  <option value="">Select canonical tag...</option>
                  {Array.from(selectedTagIds).map(tagId => {
                    const tag = tags.find(t => t.id === tagId);
                    return tag ? (
                      <option key={tagId} value={tagId}>
                        {tag.name} ({tag.storyCount || 0} stories)
                      </option>
                    ) : null;
                  })}
                </select>
              </div>

              {/* Preview Button */}
              {mergeTargetTagId && (
                <Button
                  onClick={handleMergePreview}
                  variant="secondary"
                  className="w-full"
                >
                  Preview Merge
                </Button>
              )}

              {/* Merge Preview */}
              {mergePreview && (
                <div className="bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-700 rounded-lg p-4">
                  <h3 className="font-medium theme-header mb-2">Merge Preview</h3>
                  <div className="space-y-2 text-sm theme-text">
                    <p>
                      <strong>Result:</strong> "{mergePreview.targetTagName}" with {mergePreview.totalResultStoryCount} stories
                    </p>
                    {mergePreview.aliasesToCreate && mergePreview.aliasesToCreate.length > 0 && (
                      <div>
                        <strong>Aliases to create:</strong>
                        <ul className="ml-4 mt-1 list-disc">
                          {mergePreview.aliasesToCreate.map((alias: string) => (
                            <li key={alias}>{alias}</li>
                          ))}
                        </ul>
                      </div>
                    )}
                  </div>
                </div>
              )}

              {/* Actions */}
              <div className="flex gap-3 pt-4">
                <Button
                  onClick={() => {
                    setIsMergeModalOpen(false);
                    setMergeTargetTagId('');
                    setMergePreview(null);
                  }}
                  variant="ghost"
                  className="flex-1"
                >
                  Cancel
                </Button>
                <Button
                  onClick={handleConfirmMerge}
                  variant="primary"
                  disabled={!mergeTargetTagId || merging}
                  className="flex-1"
                >
                  {merging ? 'Merging...' : 'Confirm Merge'}
                </Button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Merge Suggestions Modal */}
      {isMergeSuggestionsModalOpen && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white dark:bg-gray-800 rounded-lg p-6 max-w-4xl w-full mx-4 max-h-[80vh] overflow-y-auto">
            <h2 className="text-2xl font-bold theme-header mb-4">Merge Suggestions</h2>
            
            <div className="space-y-4">
              <p className="theme-text">
                Found {mergeSuggestions.length} potential merge opportunities based on similar tag names.
              </p>

              {mergeSuggestions.length === 0 ? (
                <div className="text-center py-8">
                  <p className="theme-text text-lg">No similar tags found.</p>
                  <p className="theme-text-muted text-sm mt-2">
                    All your tags appear to have unique names.
                  </p>
                </div>
              ) : (
                <div className="space-y-4">
                  {mergeSuggestions.map((suggestion, index) => (
                    <div
                      key={index}
                      className="border theme-border rounded-lg p-4 bg-yellow-50 dark:bg-yellow-900/20"
                    >
                      <div className="flex justify-between items-start mb-3">
                        <div>
                          <h3 className="font-medium theme-header">
                            Suggestion {index + 1}
                          </h3>
                          <p className="text-sm theme-text-muted">
                            {suggestion.reason} (Similarity: {(suggestion.similarity * 100).toFixed(1)}%)
                          </p>
                        </div>
                        <Button
                          variant="primary"
                          size="sm"
                          onClick={() => {
                            // Pre-select these tags for merging and go directly to merge modal
                            const suggestedTagIds = new Set(suggestion.group.map(tag => tag.id));
                            setSelectedTagIds(suggestedTagIds);
                            setIsMergeSuggestionsModalOpen(false);
                            
                            // Open merge modal directly
                            setIsMergeModalOpen(true);
                            setMergeTargetTagId('');
                            setMergePreview(null);
                          }}
                        >
                          Merge These
                        </Button>
                      </div>
                      
                      <div className="flex flex-wrap gap-2">
                        {suggestion.group.map((tag, tagIndex) => (
                          <div key={tag.id} className="flex items-center gap-2">
                            <TagDisplay
                              tag={tag}
                              size="sm"
                              showAliasesTooltip={true}
                              clickable={false}
                            />
                            <span className="text-xs theme-text-muted">
                              ({tag.storyCount || 0} stories)
                            </span>
                            {tagIndex < suggestion.group.length - 1 && (
                              <span className="text-gray-400">→</span>
                            )}
                          </div>
                        ))}
                      </div>
                    </div>
                  ))}
                </div>
              )}

              {/* Actions */}
              <div className="flex gap-3 pt-4 border-t theme-border">
                <Button
                  onClick={() => setIsMergeSuggestionsModalOpen(false)}
                  variant="ghost"
                  className="flex-1"
                >
                  Close
                </Button>
                {mergeSuggestions.length > 0 && (
                  <Button
                    onClick={() => {
                      // Select all suggested tags for batch processing
                      const allSuggestedTagIds = new Set<string>();
                      mergeSuggestions.forEach(suggestion => {
                        suggestion.group.forEach(tag => allSuggestedTagIds.add(tag.id));
                      });
                      setSelectedTagIds(allSuggestedTagIds);
                      setIsMergeSuggestionsModalOpen(false);
                    }}
                    variant="secondary"
                    className="flex-1"
                  >
                    Select All Suggested ({mergeSuggestions.reduce((acc, s) => acc + s.group.length, 0)} tags)
                  </Button>
                )}
              </div>
            </div>
          </div>
        </div>
      )}
    </AppLayout>
  );
}