/**
 * Global Tag Picker Component
 * Keyboard shortcut: Option+Shift+T (Mac) or Alt+Shift+T (Windows/Linux)
 */

class TagPicker {
    constructor() {
        this.modal = null;
        this.searchInput = null;
        this.resultsContainer = null;
        this.allTags = [];
        this.tagGroups = [];
        this.filteredTags = [];
        this.selectedIndex = 0;
        this.onSelectCallback = null;
        this.contextType = null; // 'ticket', 'customer', 'time_entry', etc.
        this.contextId = null;
        
        // Page level defaults (for keyboard shortcut)
        this.defaultContextType = null;
        this.defaultContextId = null;
        this.defaultOnSelectCallback = null;

        this.init();
    }

    init() {
        // Wait for DOM to be ready
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', () => this.setup());
        } else {
            this.setup();
        }
    }
    
    setup() {
        console.log('🏷️ Tag Picker: Initializing...');
        
        // Check if Bootstrap is loaded
        if (typeof bootstrap === 'undefined') {
            console.error('🏷️ Tag Picker: Bootstrap not loaded yet, retrying in 100ms');
            setTimeout(() => this.setup(), 100);
            return;
        }
        
        // Create modal HTML
        this.createModal();
        
        // Setup global keyboard listener
        document.addEventListener('keydown', (e) => {
            // Debug: Log all Alt+Shift combinations
            if (e.altKey && e.shiftKey) {
                console.log('🏷️ Alt+Shift pressed with key:', e.key, 'code:', e.code, 'keyCode:', e.keyCode);
            }
            
            // Option+Shift+T (Mac) or Alt+Shift+T (Windows/Linux)
            if (e.altKey && e.shiftKey && (e.key === 'T' || e.key === 't' || e.code === 'KeyT')) {
                e.preventDefault();
                console.log('🏷️ Tag picker shortcut triggered!');
                this.show();
            }
            
            // ESC to close
            if (e.key === 'Escape' && this.modal && this.modal.classList.contains('show')) {
                this.hide();
            }
        });
        
        console.log('🏷️ Tag Picker: Keyboard listener registered (Option+Shift+T)');
        
        // Load tags on init
        this.loadTags();
    }

    createModal() {
        const modalHTML = `
            <div class="modal fade" id="tagPickerModal" tabindex="-1" data-bs-backdrop="static" data-bs-keyboard="false">
                <div class="modal-dialog modal-dialog-centered modal-lg">
                    <div class="modal-content" style="border-radius: 16px; border: none; box-shadow: 0 10px 40px rgba(0,0,0,0.15);">
                        <div class="modal-header border-0 pb-2" style="background: linear-gradient(135deg, #0f4c75 0%, #3d8bfd 100%); color: white; border-radius: 16px 16px 0 0; padding: 1.5rem;">
                            <div class="w-100">
                                <div class="d-flex align-items-center mb-3">
                                    <i class="bi bi-tags me-2" style="font-size: 1.8rem;"></i>
                                    <h5 class="modal-title mb-0" style="font-weight: 600; font-size: 1.3rem;">Tilføj Tag</h5>
                                    <button type="button" class="btn-close btn-close-white ms-auto" data-bs-dismiss="modal"></button>
                                </div>
                                <input 
                                    type="text" 
                                    class="form-control form-control-lg" 
                                    id="tagPickerSearch" 
                                    placeholder="🔍 Søg efter tag..." 
                                    autocomplete="off"
                                    style="border: none; border-radius: 12px; padding: 0.75rem 1rem; font-size: 1rem; box-shadow: 0 4px 12px rgba(0,0,0,0.1);"
                                >
                                <div class="mt-2" style="font-size: 0.85rem; opacity: 0.9;">
                                    <kbd style="background: rgba(255,255,255,0.2); color: white; padding: 0.25rem 0.5rem; border-radius: 4px;">⌥</kbd> 
                                    <kbd style="background: rgba(255,255,255,0.2); color: white; padding: 0.25rem 0.5rem; border-radius: 4px;">⇧</kbd> 
                                    <kbd style="background: rgba(255,255,255,0.2); color: white; padding: 0.25rem 0.5rem; border-radius: 4px;">T</kbd> 
                                    for at åbne • 
                                    <kbd style="background: rgba(255,255,255,0.2); color: white; padding: 0.25rem 0.5rem; border-radius: 4px;">↑</kbd> 
                                    <kbd style="background: rgba(255,255,255,0.2); color: white; padding: 0.25rem 0.5rem; border-radius: 4px;">↓</kbd> 
                                    for at navigere • 
                                    <kbd style="background: rgba(255,255,255,0.2); color: white; padding: 0.25rem 0.5rem; border-radius: 4px;">Enter</kbd> 
                                    for at vælge
                                </div>
                            </div>
                        </div>
                        <div class="modal-body pt-3" style="max-height: 500px; overflow-y: auto; padding: 1.5rem;">
                            <div id="tagPickerResults"></div>
                        </div>
                    </div>
                </div>
            </div>
        `;
        
        document.body.insertAdjacentHTML('beforeend', modalHTML);
        
        this.modal = document.getElementById('tagPickerModal');
        this.searchInput = document.getElementById('tagPickerSearch');
        this.resultsContainer = document.getElementById('tagPickerResults');
        
        // Setup search input
        this.searchInput.addEventListener('input', () => {
            this.filterTags(this.searchInput.value);
        });
        
        // Keyboard navigation
        this.searchInput.addEventListener('keydown', (e) => {
            if (e.key === 'ArrowDown') {
                e.preventDefault();
                this.selectedIndex = Math.min(this.selectedIndex + 1, this.filteredTags.length - 1);
                this.renderResults();
            } else if (e.key === 'ArrowUp') {
                e.preventDefault();
                this.selectedIndex = Math.max(this.selectedIndex - 1, 0);
                this.renderResults();
            } else if (e.key === 'Enter') {
                e.preventDefault();
                this.selectTag(this.filteredTags[this.selectedIndex]);
            }
        });
        
        // Reset on modal close
        this.modal.addEventListener('hidden.bs.modal', () => {
            this.searchInput.value = '';
            this.selectedIndex = 0;
            this.contextType = null;
            this.contextId = null;
            this.onSelectCallback = null;
        });
    }

    async loadTags() {
        try {
            console.log('🏷️ Loading tags from API...');
            const response = await fetch('/api/v1/tags?is_active=true');
            if (!response.ok) throw new Error('Failed to load tags');
            this.allTags = await response.json();
            // Tag groups are optional metadata. Some hubs do not expose the endpoint,
            // so keep picker resilient by not depending on a second API call.
            this.tagGroups = [];
            console.log('🏷️ Loaded tags:', this.allTags.length);
            this.filteredTags = [...this.allTags];
            this.renderResults();
        } catch (error) {
            console.error('🏷️ Error loading tags:', error);
        }
    }

    filterTags(query) {
        if (!query.trim()) {
            this.filteredTags = [...this.allTags];
        } else {
            const lowerQuery = query.toLowerCase();
            this.filteredTags = this.allTags.filter(tag => 
                tag.name.toLowerCase().includes(lowerQuery) ||
                (tag.description && tag.description.toLowerCase().includes(lowerQuery))
            );
        }
        this.selectedIndex = 0;
        this.renderResults();
    }

    renderResults() {
        if (this.filteredTags.length === 0) {
            this.resultsContainer.innerHTML = `
                <div class="text-center text-muted py-4">
                    <i class="bi bi-search" style="font-size: 2rem;"></i>
                    <p class="mt-2">Ingen tags fundet</p>
                </div>
            `;
            return;
        }

        // Group by type
        const grouped = this.filteredTags.reduce((acc, tag) => {
            if (!acc[tag.type]) acc[tag.type] = [];
            acc[tag.type].push(tag);
            return acc;
        }, {});

        const typeLabels = {
            'workflow': '⚡ Workflow - Automatisering',
            'status': '📊 Status - Tilstand',
            'category': '📁 Kategori - Emne',
            'priority': '🔥 Prioritet - Hastighed',
            'billing': '💰 Fakturering - Økonomi',
            'brand': '🏷️ Brand - Leverandør/produkt',
            'type': '🧩 Type - Sagstype'
        };

        const typeOrder = ['workflow', 'status', 'category', 'priority', 'billing', 'brand', 'type'];

        let html = '';
        typeOrder.forEach(type => {
            if (grouped[type]) {
                html += `<div class="mb-4">
                    <div class="text-uppercase fw-bold mb-2" style="font-size: 0.75rem; letter-spacing: 1px; color: #6c757d;">${typeLabels[type]}</div>
                    <div class="list-group" style="border-radius: 12px; overflow: hidden; border: 1px solid #e9ecef;">`;
                
                grouped[type].forEach((tag, index) => {
                    const globalIndex = this.filteredTags.indexOf(tag);
                    const isSelected = globalIndex === this.selectedIndex;
                    const group = this.tagGroups?.find(g => g.id === tag.tag_group_id);
                    const groupHint = group ? ` · ${group.name} (${group.behavior})` : '';
                    html += `
                        <a href="#" 
                           class="list-group-item list-group-item-action d-flex align-items-center ${isSelected ? 'active' : ''}"
                           data-tag-id="${tag.id}"
                           style="border: none; border-bottom: 1px solid #f0f0f0; padding: 1rem; transition: all 0.2s; ${isSelected ? 'background: linear-gradient(135deg, #0f4c75 0%, #3d8bfd 100%); color: white;' : ''}"
                           onclick="window.tagPicker.selectTag(${JSON.stringify(tag).replace(/"/g, '&quot;')}); return false;">
                            <span class="badge me-3" style="background-color: ${tag.color}; min-width: 32px; height: 32px; border-radius: 8px; display: flex; align-items: center; justify-content: center; font-size: 1.1rem;">
                                ${tag.icon ? `<i class="bi ${tag.icon}" style="color: white;"></i>` : ''}
                            </span>
                            <div class="flex-grow-1">
                                <div class="fw-bold" style="font-size: 0.95rem;">${tag.name}</div>
                                ${tag.description ? `<small class="${isSelected ? 'text-white-50' : 'text-muted'}" style="font-size: 0.8rem;">${tag.description}${groupHint}</small>` : groupHint ? `<small class="${isSelected ? 'text-white-50' : 'text-muted'}" style="font-size: 0.8rem;">${groupHint}</small>` : ''}
                            </div>
                            ${!isSelected ? `<i class="bi bi-plus-circle text-primary" style="font-size: 1.2rem;"></i>` : ''}
                        </a>
                    `;
                });
                
                html += `</div></div>`;
            }
        });

        this.resultsContainer.innerHTML = html;

        // Scroll selected into view
        const selected = this.resultsContainer.querySelector('.active');
        if (selected) {
            selected.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
        }
    }

    async selectTag(tag) {
        if (!tag) return;
        
        console.log(`🏷️ Selecting tag ${tag.name} for context: ${this.contextType} #${this.contextId}`);

        // If context provided, add tag to entity
        let addResult = null;
        if (this.contextType && this.contextId) {
            try {
                const response = await fetch('/api/v1/tags/entity', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        entity_type: this.contextType,
                        entity_id: this.contextId,
                        tag_id: tag.id
                    })
                });

                if (!response.ok) {
                    let errorDetail = '';
                    try {
                        const error = await response.json();
                        errorDetail = String(error?.detail || '');
                    } catch (parseError) {
                        errorDetail = '';
                    }

                    if (response.status === 409 || errorDetail.toLowerCase().includes('already exists')) {
                        alert('Dette tag er allerede tilføjet');
                        return;
                    }

                    // Backward compatibility: some case pages still persist tags via /sag/{id}/tags.
                    if (String(this.contextType).toLowerCase() === 'case') {
                        const legacyResponse = await fetch(`/api/v1/sag/${this.contextId}/tags`, {
                            method: 'POST',
                            headers: { 'Content-Type': 'application/json' },
                            credentials: 'include',
                            body: JSON.stringify({ tag_navn: tag.name })
                        });

                        if (legacyResponse.ok) {
                            addResult = { action: null };
                            this.showSuccess(tag.name);
                        } else {
                            let legacyErrorDetail = '';
                            try {
                                const legacyError = await legacyResponse.json();
                                legacyErrorDetail = String(legacyError?.detail || '');
                            } catch (parseError) {
                                legacyErrorDetail = '';
                            }
                            throw new Error(legacyErrorDetail || errorDetail || 'Kunne ikke tilføje tag');
                        }
                    } else {
                        throw new Error(errorDetail || 'Kunne ikke tilføje tag');
                    }
                } else {
                    try {
                        addResult = await response.json();
                    } catch (parseError) {
                        addResult = { action: null };
                    }
                    // Show success feedback
                    this.showSuccess(tag.name);
                }
            } catch (error) {
                console.error('Error adding tag:', error);
                alert('Fejl ved tilføjelse af tag: ' + error.message);
                return;
            }
        }

        // Call callback if provided
        if (this.onSelectCallback) {
            this.onSelectCallback(tag, addResult);
        }

        if (addResult && addResult.action) {
            this.runTagAction(tag, addResult.action);
        }

        this.hide();
    }

    runTagAction(tag, action) {
        if (!action || !action.type) {
            return;
        }

        const detail = {
            tag,
            action,
            entity_type: this.contextType,
            entity_id: this.contextId,
        };

        window.dispatchEvent(new CustomEvent('hub:tag-action', { detail }));
    }

    show(contextType = null, contextId = null, onSelect = null) {
        // Use provided context OR fall back to page defaults
        // Note: arguments are undefined if not passed, so check for null/undefined
        this.contextType = (contextType !== null && contextType !== undefined) ? contextType : this.defaultContextType;
        this.contextId = (contextId !== null && contextId !== undefined) ? contextId : this.defaultContextId;
        this.onSelectCallback = onSelect || this.defaultOnSelectCallback;
        
        console.log(`🏷️ Showing Tag Picker. Context: ${this.contextType} #${this.contextId}`);
        
        const modalInstance = new bootstrap.Modal(this.modal);
        modalInstance.show();
        
        // Focus search input after modal is shown
        this.modal.addEventListener('shown.bs.modal', () => {
            this.searchInput.focus();
        }, { once: true });
    }

    setPageContext(contextType, contextId, onSelect = null) {
        console.log(`🏷️ Tag Picker: Setting page context to ${contextType} #${contextId}`);
        this.defaultContextType = contextType;
        this.defaultContextId = contextId;
        this.defaultOnSelectCallback = onSelect;
    }

    hide() {
        const modalInstance = bootstrap.Modal.getInstance(this.modal);
        if (modalInstance) {
            modalInstance.hide();
        }
    }

    showSuccess(tagName) {
        // Create toast notification
        const toastHTML = `
            <div class="toast-container position-fixed top-0 end-0 p-3">
                <div class="toast show" role="alert">
                    <div class="toast-header bg-success text-white">
                        <i class="bi bi-check-circle me-2"></i>
                        <strong class="me-auto">Tag tilføjet</strong>
                        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="toast"></button>
                    </div>
                    <div class="toast-body">
                        Tag "${tagName}" er tilføjet
                    </div>
                </div>
            </div>
        `;
        
        document.body.insertAdjacentHTML('beforeend', toastHTML);
        const toastEl = document.querySelector('.toast-container .toast');
        setTimeout(() => toastEl.remove(), 3000);
    }
}

// Initialize global tag picker
window.tagPicker = new TagPicker();

// Helper function to show tag picker with context
window.showTagPicker = function(entityType, entityId, onSelect = null) {
    window.tagPicker.show(entityType, entityId, onSelect);
};

// Helper to set default context (for keyboard shortcuts)
window.setTagPickerContext = function(entityType, entityId, onSelect = null) {
    if (window.tagPicker) {
        window.tagPicker.setPageContext(entityType, entityId, onSelect);
    } else {
        // Retry if not initialized yet
        document.addEventListener('DOMContentLoaded', () => {
            if (window.tagPicker) {
                window.tagPicker.setPageContext(entityType, entityId, onSelect);
            }
        });
    }
};

// Helper function to render tags for an entity
window.renderEntityTags = async function(entityType, entityId, containerId) {
    try {
        const response = await fetch(`/api/v1/tags/entity/${entityType}/${entityId}`);
        if (!response.ok) return;
        
        const tags = await response.json();
        const container = document.getElementById(containerId);
        
        if (!container) return;
        
        container.innerHTML = tags.map(tag => `
            <span class="badge me-1 mb-1" style="background-color: ${tag.color};">
                ${tag.icon ? `<i class="bi ${tag.icon}"></i> ` : ''}${tag.name}
                <button type="button" class="btn-close btn-close-white btn-sm ms-1" 
                        onclick="removeEntityTag('${entityType}', ${entityId}, ${tag.id}, '${containerId}')"
                        style="font-size: 0.6rem; vertical-align: middle;"></button>
            </span>
        `).join('');
    } catch (error) {
        console.error('Error rendering tags:', error);
    }
};

// Helper function to remove tag from entity
window.removeEntityTag = async function(entityType, entityId, tagId, containerId) {
    if (!confirm('Fjern dette tag?')) return;
    
    try {
        console.log(`🏷️ Removing tag ${tagId} from ${entityType} #${entityId}`);
        // Use path-based endpoint for better compatibility
        const response = await fetch(`/api/v1/tags/entity/${entityType}/${entityId}/${tagId}`, {
            method: 'DELETE'
        });
        
        if (!response.ok) {
            const errorText = await response.text();
            throw new Error(`Failed to remove tag: ${response.status} ${errorText}`);
        }
        
        console.log('🏷️ Tag removed successfully');
        // Refresh tags display
        await window.renderEntityTags(entityType, entityId, containerId);
    } catch (error) {
        console.error('Error removing tag:', error);
        alert('Fejl ved fjernelse af tag: ' + error.message);
    }
};
