/**
 * Media Tag UI Components
 * UI elements and controls for the media tagging system
 */

class MediaTagUI {
    constructor(tagManager) {
        this.tagManager = tagManager;
        this.selectedMedia = new Set();
        this.bulkMode = false;
        this.filterMode = 'any'; // 'any' or 'all'
        this.activeFilters = new Set();
        
        console.log('🎨 MediaTagUI initialized');
    }

    /**
     * Render tag input with autocomplete
     * @param {HTMLElement} container - Container element
     * @param {string} mediaId - Optional media ID for single-item tagging
     * @returns {HTMLElement} Tag input element
     */
    renderTagInput(container, mediaId = null) {
        const wrapper = document.createElement('div');
        wrapper.className = 'tag-input-wrapper';
        
        wrapper.innerHTML = `
            <div class="tag-input-container">
                <input 
                    type="text" 
                    class="tag-input" 
                    placeholder="Add tags (comma separated)..."
                    autocomplete="off"
                />
                <button class="btn btn-primary btn-small add-tag-btn">
                    <span>+</span> Add
                </button>
            </div>
            <div class="tag-suggestions" style="display: none;"></div>
        `;

        const input = wrapper.querySelector('.tag-input');
        const addButton = wrapper.querySelector('.add-tag-btn');
        const suggestions = wrapper.querySelector('.tag-suggestions');

        // Autocomplete functionality
        input.addEventListener('input', (e) => {
            const query = e.target.value.trim();
            if (query.length > 0) {
                const matches = this.tagManager.searchTags(query);
                this.renderSuggestions(suggestions, matches, input);
            } else {
                suggestions.style.display = 'none';
            }
        });

        // Add tag on button click
        addButton.addEventListener('click', () => {
            this.handleAddTags(input.value, mediaId);
            input.value = '';
            suggestions.style.display = 'none';
        });

        // Add tag on Enter key
        input.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                e.preventDefault();
                this.handleAddTags(input.value, mediaId);
                input.value = '';
                suggestions.style.display = 'none';
            }
        });

        // Close suggestions on outside click
        document.addEventListener('click', (e) => {
            if (!wrapper.contains(e.target)) {
                suggestions.style.display = 'none';
            }
        });

        container.appendChild(wrapper);
        return wrapper;
    }

    /**
     * Render tag suggestions dropdown
     */
    renderSuggestions(container, tags, input) {
        if (tags.length === 0) {
            container.style.display = 'none';
            return;
        }

        container.innerHTML = tags.map(tag => `
            <div class="tag-suggestion" data-tag-name="${tag.name}">
                <span class="tag-color-dot" style="background-color: ${tag.color}"></span>
                <span class="tag-name">${tag.name}</span>
                <span class="tag-usage">(${tag.usageCount})</span>
            </div>
        `).join('');

        container.style.display = 'block';

        // Add click handlers to suggestions
        container.querySelectorAll('.tag-suggestion').forEach(suggestion => {
            suggestion.addEventListener('click', () => {
                const tagName = suggestion.dataset.tagName;
                input.value = tagName;
                container.style.display = 'none';
                input.focus();
            });
        });
    }

    /**
     * Handle adding tags
     */
    handleAddTags(inputValue, mediaId = null) {
        const tagNames = inputValue
            .split(',')
            .map(t => t.trim())
            .filter(t => t.length > 0);

        if (tagNames.length === 0) {
            return;
        }

        try {
            if (this.bulkMode && this.selectedMedia.size > 0) {
                // Bulk tagging
                const mediaIds = Array.from(this.selectedMedia);
                const result = this.tagManager.bulkAddTags(mediaIds, tagNames);
                this.showNotification(
                    `Added tags to ${result.successCount} items`,
                    'success'
                );
                this.onTagsChanged();
            } else if (mediaId) {
                // Single item tagging
                this.tagManager.addTagsToMedia(mediaId, tagNames);
                this.showNotification(`Added ${tagNames.length} tag(s)`, 'success');
                this.onTagsChanged();
            } else {
                this.showNotification('No media selected', 'warning');
            }
        } catch (error) {
            this.showNotification(error.message, 'error');
        }
    }

    /**
     * Render tag chips for a media item
     * @param {HTMLElement} container - Container element
     * @param {string} mediaId - Media ID
     * @param {boolean} editable - Whether tags can be removed
     */
    renderMediaTags(container, mediaId, editable = true) {
        const tags = this.tagManager.getTagsForMedia(mediaId);
        
        container.innerHTML = '';
        container.className = 'media-tags-container';

        if (tags.length === 0) {
            container.innerHTML = '<span class="no-tags-label">No tags</span>';
            return;
        }

        tags.forEach(tag => {
            const chip = document.createElement('span');
            chip.className = 'tag-chip';
            chip.style.backgroundColor = tag.color;
            chip.innerHTML = `
                <span class="tag-chip-name">${tag.name}</span>
                ${editable ? `<span class="tag-chip-remove" data-tag-id="${tag.id}" data-media-id="${mediaId}">×</span>` : ''}
            `;
            
            if (editable) {
                const removeBtn = chip.querySelector('.tag-chip-remove');
                removeBtn.addEventListener('click', (e) => {
                    e.stopPropagation();
                    this.handleRemoveTag(mediaId, tag.id);
                });
            }

            container.appendChild(chip);
        });
    }

    /**
     * Handle removing a tag from media
     */
    handleRemoveTag(mediaId, tagId) {
        const tag = this.tagManager.getTagById(tagId);
        const tagName = tag ? tag.name : 'tag';

        if (confirm(`Remove "${tagName}" from this media?`)) {
            this.tagManager.removeTagFromMedia(mediaId, tagId);
            this.showNotification('Tag removed', 'success');
            this.onTagsChanged();
        }
    }

    /**
     * Render tag management modal
     */
    renderTagManagementModal() {
        const modal = document.createElement('div');
        modal.className = 'modal tag-management-modal';
        modal.id = 'tag-management-modal';
        
        modal.innerHTML = `
            <div class="modal-overlay"></div>
            <div class="modal-content">
                <div class="modal-header">
                    <h2>Manage Tags</h2>
                    <button class="modal-close-btn">×</button>
                </div>
                <div class="modal-body">
                    <div class="tag-management-section">
                        <h3>Create New Tag</h3>
                        <div class="tag-create-form">
                            <input type="text" class="tag-name-input" placeholder="Tag name..." />
                            <input type="color" class="tag-color-input" value="${this.tagManager.generateRandomColor()}" />
                            <button class="btn btn-primary create-tag-btn">Create Tag</button>
                        </div>
                    </div>
                    
                    <div class="tag-management-section">
                        <h3>All Tags (${this.tagManager.getAllTags().length})</h3>
                        <div class="tag-search-box">
                            <input type="text" class="tag-search-input" placeholder="Search tags..." />
                        </div>
                        <div class="all-tags-list"></div>
                    </div>

                    <div class="tag-management-section">
                        <h3>Statistics</h3>
                        <div class="tag-statistics"></div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button class="btn btn-outline close-modal-btn">Close</button>
                </div>
            </div>
        `;

        document.body.appendChild(modal);

        // Setup event listeners
        this.setupTagManagementModal(modal);
        this.updateTagList(modal);
        this.updateTagStatistics(modal);

        return modal;
    }

    /**
     * Setup tag management modal event listeners
     */
    setupTagManagementModal(modal) {
        const overlay = modal.querySelector('.modal-overlay');
        const closeBtn = modal.querySelector('.modal-close-btn');
        const closeModalBtn = modal.querySelector('.close-modal-btn');
        const createBtn = modal.querySelector('.create-tag-btn');
        const nameInput = modal.querySelector('.tag-name-input');
        const colorInput = modal.querySelector('.tag-color-input');
        const searchInput = modal.querySelector('.tag-search-input');

        // Close modal handlers
        const closeModal = () => {
            modal.classList.remove('active');
            setTimeout(() => modal.remove(), 300);
        };

        overlay.addEventListener('click', closeModal);
        closeBtn.addEventListener('click', closeModal);
        closeModalBtn.addEventListener('click', closeModal);

        // Create tag
        createBtn.addEventListener('click', () => {
            const name = nameInput.value.trim();
            const color = colorInput.value;

            if (!name) {
                this.showNotification('Tag name is required', 'warning');
                return;
            }

            try {
                this.tagManager.createTag(name, color);
                this.showNotification(`Tag "${name}" created`, 'success');
                nameInput.value = '';
                colorInput.value = this.tagManager.generateRandomColor();
                this.updateTagList(modal);
                this.updateTagStatistics(modal);
                this.onTagsChanged();
            } catch (error) {
                this.showNotification(error.message, 'error');
            }
        });

        // Search tags
        searchInput.addEventListener('input', (e) => {
            const query = e.target.value;
            this.updateTagList(modal, query);
        });

        // Create tag on Enter
        nameInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                createBtn.click();
            }
        });
    }

    /**
     * Update tag list in management modal
     */
    updateTagList(modal, searchQuery = '') {
        const container = modal.querySelector('.all-tags-list');
        const tags = searchQuery 
            ? this.tagManager.searchTags(searchQuery)
            : this.tagManager.getAllTags();

        if (tags.length === 0) {
            container.innerHTML = '<p class="no-results">No tags found</p>';
            return;
        }

        // Sort by usage count
        tags.sort((a, b) => b.usageCount - a.usageCount);

        container.innerHTML = tags.map(tag => `
            <div class="tag-item" data-tag-id="${tag.id}">
                <div class="tag-item-color" style="background-color: ${tag.color}">
                    <input type="color" class="tag-color-picker" value="${tag.color}" data-tag-id="${tag.id}" />
                </div>
                <div class="tag-item-info">
                    <span class="tag-item-name">${tag.name}</span>
                    <span class="tag-item-usage">${tag.usageCount} uses</span>
                </div>
                <div class="tag-item-actions">
                    <button class="btn btn-small btn-outline rename-tag-btn" data-tag-id="${tag.id}">Rename</button>
                    <button class="btn btn-small btn-danger delete-tag-btn" data-tag-id="${tag.id}">Delete</button>
                </div>
            </div>
        `).join('');

        // Add event listeners
        container.querySelectorAll('.delete-tag-btn').forEach(btn => {
            btn.addEventListener('click', () => {
                const tagId = btn.dataset.tagId;
                const tag = this.tagManager.getTagById(tagId);
                if (confirm(`Delete tag "${tag.name}"? This will remove it from all media.`)) {
                    this.tagManager.deleteTag(tagId);
                    this.showNotification('Tag deleted', 'success');
                    this.updateTagList(modal, searchQuery);
                    this.updateTagStatistics(modal);
                    this.onTagsChanged();
                }
            });
        });

        container.querySelectorAll('.rename-tag-btn').forEach(btn => {
            btn.addEventListener('click', () => {
                const tagId = btn.dataset.tagId;
                const tag = this.tagManager.getTagById(tagId);
                const newName = prompt(`Rename tag "${tag.name}" to:`, tag.name);
                if (newName && newName.trim()) {
                    try {
                        this.tagManager.renameTag(tagId, newName);
                        this.showNotification('Tag renamed', 'success');
                        this.updateTagList(modal, searchQuery);
                        this.onTagsChanged();
                    } catch (error) {
                        this.showNotification(error.message, 'error');
                    }
                }
            });
        });

        container.querySelectorAll('.tag-color-picker').forEach(picker => {
            picker.addEventListener('change', (e) => {
                const tagId = e.target.dataset.tagId;
                const newColor = e.target.value;
                this.tagManager.updateTagColor(tagId, newColor);
                this.showNotification('Tag color updated', 'success');
                this.onTagsChanged();
            });
        });
    }

    /**
     * Update tag statistics in management modal
     */
    updateTagStatistics(modal) {
        const container = modal.querySelector('.tag-statistics');
        const stats = this.tagManager.getStatistics();

        container.innerHTML = `
            <div class="stat-grid">
                <div class="stat-item">
                    <div class="stat-value">${stats.totalTags}</div>
                    <div class="stat-label">Total Tags</div>
                </div>
                <div class="stat-item">
                    <div class="stat-value">${stats.totalTaggedMedia}</div>
                    <div class="stat-label">Tagged Media</div>
                </div>
                <div class="stat-item">
                    <div class="stat-value">${stats.averageTagsPerMedia.toFixed(1)}</div>
                    <div class="stat-label">Avg Tags/Media</div>
                </div>
            </div>
            ${stats.mostUsedTags.length > 0 ? `
                <div class="most-used-tags">
                    <h4>Most Used Tags</h4>
                    <div class="tag-cloud">
                        ${stats.mostUsedTags.map(tag => `
                            <span class="tag-chip" style="background-color: ${tag.color}">
                                ${tag.name} (${tag.usageCount})
                            </span>
                        `).join('')}
                    </div>
                </div>
            ` : ''}
        `;
    }

    /**
     * Render tag filter panel
     * @param {HTMLElement} container - Container element
     */
    renderTagFilter(container) {
        const wrapper = document.createElement('div');
        wrapper.className = 'tag-filter-panel';
        
        wrapper.innerHTML = `
            <div class="tag-filter-header">
                <h3>Filter by Tags</h3>
                <div class="filter-mode-toggle">
                    <button class="filter-mode-btn active" data-mode="any">Any</button>
                    <button class="filter-mode-btn" data-mode="all">All</button>
                </div>
            </div>
            <div class="tag-filter-list"></div>
            <div class="tag-filter-actions">
                <button class="btn btn-small btn-outline clear-filters-btn">Clear Filters</button>
            </div>
        `;

        container.appendChild(wrapper);

        // Setup event listeners
        this.setupTagFilterPanel(wrapper);
        this.updateTagFilterList(wrapper);

        return wrapper;
    }

    /**
     * Setup tag filter panel event listeners
     */
    setupTagFilterPanel(panel) {
        const modeButtons = panel.querySelectorAll('.filter-mode-btn');
        const clearBtn = panel.querySelector('.clear-filters-btn');

        // Mode toggle
        modeButtons.forEach(btn => {
            btn.addEventListener('click', () => {
                modeButtons.forEach(b => b.classList.remove('active'));
                btn.classList.add('active');
                this.filterMode = btn.dataset.mode;
                this.onFilterChanged();
            });
        });

        // Clear filters
        clearBtn.addEventListener('click', () => {
            this.activeFilters.clear();
            this.updateTagFilterList(panel);
            this.onFilterChanged();
        });
    }

    /**
     * Update tag filter list
     */
    updateTagFilterList(panel) {
        const container = panel.querySelector('.tag-filter-list');
        const tags = this.tagManager.getAllTags();

        if (tags.length === 0) {
            container.innerHTML = '<p class="no-tags">No tags available</p>';
            return;
        }

        // Sort alphabetically
        tags.sort((a, b) => a.name.localeCompare(b.name));

        container.innerHTML = tags.map(tag => `
            <div class="tag-filter-item ${this.activeFilters.has(tag.id) ? 'active' : ''}" data-tag-id="${tag.id}">
                <input 
                    type="checkbox" 
                    class="tag-filter-checkbox" 
                    id="filter-${tag.id}"
                    ${this.activeFilters.has(tag.id) ? 'checked' : ''}
                />
                <label for="filter-${tag.id}">
                    <span class="tag-color-dot" style="background-color: ${tag.color}"></span>
                    <span class="tag-name">${tag.name}</span>
                    <span class="tag-count">(${tag.usageCount})</span>
                </label>
            </div>
        `).join('');

        // Add event listeners
        container.querySelectorAll('.tag-filter-checkbox').forEach(checkbox => {
            checkbox.addEventListener('change', (e) => {
                const tagId = e.target.closest('.tag-filter-item').dataset.tagId;
                if (e.target.checked) {
                    this.activeFilters.add(tagId);
                } else {
                    this.activeFilters.delete(tagId);
                }
                e.target.closest('.tag-filter-item').classList.toggle('active', e.target.checked);
                this.onFilterChanged();
            });
        });
    }

    /**
     * Enable bulk selection mode
     */
    enableBulkMode() {
        this.bulkMode = true;
        this.selectedMedia.clear();
        console.log('🏷️ Bulk mode enabled');
    }

    /**
     * Disable bulk selection mode
     */
    disableBulkMode() {
        this.bulkMode = false;
        this.selectedMedia.clear();
        console.log('🏷️ Bulk mode disabled');
    }

    /**
     * Toggle media selection
     */
    toggleMediaSelection(mediaId) {
        if (this.selectedMedia.has(mediaId)) {
            this.selectedMedia.delete(mediaId);
        } else {
            this.selectedMedia.add(mediaId);
        }
        console.log(`🏷️ Selected media count: ${this.selectedMedia.size}`);
    }

    /**
     * Select all media
     */
    selectAllMedia(mediaIds) {
        mediaIds.forEach(id => this.selectedMedia.add(id));
        console.log(`🏷️ Selected all ${mediaIds.length} media items`);
    }

    /**
     * Clear selection
     */
    clearSelection() {
        this.selectedMedia.clear();
        console.log('🏷️ Selection cleared');
    }

    /**
     * Get filtered media based on active tag filters
     */
    getFilteredMedia(allMedia) {
        if (this.activeFilters.size === 0) {
            return allMedia;
        }

        const tagIds = Array.from(this.activeFilters);
        const filteredIds = this.filterMode === 'all'
            ? this.tagManager.getMediaWithAllTags(tagIds)
            : this.tagManager.getMediaWithAnyTags(tagIds);

        return allMedia.filter(media => {
            const mediaId = media.id || media.path || media.filename;
            return filteredIds.includes(mediaId);
        });
    }

    /**
     * Callback when tags change
     */
    onTagsChanged() {
        // Override this method to handle tag changes
        console.log('🏷️ Tags changed');
        
        // Dispatch custom event
        window.dispatchEvent(new CustomEvent('tagsChanged', {
            detail: {
                tags: this.tagManager.getAllTags(),
                statistics: this.tagManager.getStatistics()
            }
        }));
    }

    /**
     * Callback when filters change
     */
    onFilterChanged() {
        // Override this method to handle filter changes
        console.log('🏷️ Filters changed:', Array.from(this.activeFilters));
        
        // Dispatch custom event
        window.dispatchEvent(new CustomEvent('tagFiltersChanged', {
            detail: {
                activeFilters: Array.from(this.activeFilters),
                filterMode: this.filterMode
            }
        }));
    }

    /**
     * Show notification
     */
    showNotification(message, type = 'info') {
        if (window.game && window.game.showNotification) {
            window.game.showNotification(message, type);
        } else {
            console.log(`[${type.toUpperCase()}] ${message}`);
        }
    }

    /**
     * Open tag management modal
     */
    openTagManagementModal() {
        // Remove existing modal if present
        const existing = document.getElementById('tag-management-modal');
        if (existing) {
            existing.remove();
        }

        const modal = this.renderTagManagementModal();
        setTimeout(() => modal.classList.add('active'), 10);
    }
}

// Make available globally
if (typeof window !== 'undefined') {
    window.MediaTagUI = MediaTagUI;
}
