/**
 * Nomor Perkara Autocomplete Component
 * Komponen untuk auto-complete nomor perkara dari database arsip SIPP
 */
class NomorPerkaraAutocomplete {
    constructor(inputSelector, options = {}) {
        this.input = typeof inputSelector === 'string' 
            ? document.querySelector(inputSelector) 
            : inputSelector;
            
        if (!this.input) {
            console.error('Input element not found');
            return;
        }
        
        this.options = {
            apiUrl: 'api/search-nomor-perkara.php',
            minLength: 2,
            debounceDelay: 300,
            maxResults: 10,
            showDetails: true,
            onSelect: null,
            ...options
        };
        
        this.currentIndex = -1;
        this.searchTimeout = null;
        this.suggestions = null;
        
        this.init();
    }
    
    init() {
        this.createSuggestionsContainer();
        this.bindEvents();
        this.addStyles();
    }
    
    createSuggestionsContainer() {
        // Wrap input in container if not already wrapped
        if (!this.input.parentElement.classList.contains('autocomplete-container')) {
            const wrapper = document.createElement('div');
            wrapper.className = 'autocomplete-container';
            this.input.parentNode.insertBefore(wrapper, this.input);
            wrapper.appendChild(this.input);
        }
        
        // Create suggestions container
        this.suggestions = document.createElement('div');
        this.suggestions.className = 'autocomplete-suggestions';
        this.input.parentElement.appendChild(this.suggestions);
    }
    
    addStyles() {
        if (!document.getElementById('autocomplete-styles')) {
            const style = document.createElement('style');
            style.id = 'autocomplete-styles';
            style.textContent = `
                .autocomplete-container {
                    position: relative;
                }
                .autocomplete-suggestions {
                    position: absolute;
                    top: 100%;
                    left: 0;
                    right: 0;
                    background: white;
                    border: 1px solid #ddd;
                    border-top: none;
                    border-radius: 0 0 4px 4px;
                    max-height: 300px;
                    overflow-y: auto;
                    z-index: 1000;
                    display: none;
                    box-shadow: 0 4px 6px rgba(0,0,0,0.1);
                }
                .autocomplete-suggestion {
                    padding: 10px 15px;
                    cursor: pointer;
                    border-bottom: 1px solid #f0f0f0;
                    transition: background-color 0.2s;
                }
                .autocomplete-suggestion:hover,
                .autocomplete-suggestion.selected {
                    background-color: #f8f9fa;
                }
                .autocomplete-suggestion:last-child {
                    border-bottom: none;
                }
                .suggestion-main {
                    font-weight: 600;
                    color: #212529;
                }
                .suggestion-detail {
                    font-size: 0.85em;
                    color: #6c757d;
                    margin-top: 2px;
                }
                .autocomplete-loading {
                    padding: 10px 15px;
                    text-align: center;
                    color: #6c757d;
                }
                .autocomplete-no-results {
                    padding: 10px 15px;
                    text-align: center;
                    color: #6c757d;
                    font-style: italic;
                }
                .autocomplete-source {
                    padding: 5px 15px;
                    background-color: #e7f3ff;
                    border-bottom: 1px solid #bee5eb;
                    font-size: 0.8em;
                    color: #0c5460;
                    text-align: center;
                }
            `;
            document.head.appendChild(style);
        }
    }
    
    bindEvents() {
        this.input.addEventListener('input', (e) => {
            this.handleInput(e.target.value);
        });
        
        this.input.addEventListener('keydown', (e) => {
            this.handleKeydown(e);
        });
        
        this.input.addEventListener('blur', () => {
            setTimeout(() => this.hideSuggestions(), 200);
        });
        
        this.input.addEventListener('focus', () => {
            if (this.input.value.length >= this.options.minLength) {
                this.search(this.input.value);
            }
        });
        
        document.addEventListener('click', (e) => {
            if (!e.target.closest('.autocomplete-container')) {
                this.hideSuggestions();
            }
        });
    }
    
    handleInput(value) {
        clearTimeout(this.searchTimeout);
        
        if (value.length < this.options.minLength) {
            this.hideSuggestions();
            return;
        }
        
        this.searchTimeout = setTimeout(() => {
            this.search(value);
        }, this.options.debounceDelay);
    }
    
    handleKeydown(e) {
        const items = this.suggestions.querySelectorAll('.autocomplete-suggestion');
        
        switch(e.key) {
            case 'ArrowDown':
                e.preventDefault();
                this.currentIndex = Math.min(this.currentIndex + 1, items.length - 1);
                this.updateSelection(items);
                break;
                
            case 'ArrowUp':
                e.preventDefault();
                this.currentIndex = Math.max(this.currentIndex - 1, -1);
                this.updateSelection(items);
                break;
                
            case 'Enter':
                e.preventDefault();
                if (this.currentIndex >= 0 && items[this.currentIndex]) {
                    this.selectSuggestion(items[this.currentIndex]);
                }
                break;
                
            case 'Escape':
                this.hideSuggestions();
                break;
        }
    }
    
    updateSelection(items) {
        items.forEach((item, index) => {
            item.classList.toggle('selected', index === this.currentIndex);
        });
    }
    
    async search(query) {
        this.showLoading();
        
        try {
            // Try primary API first (SIPP online)
            const response = await fetch(`${this.options.apiUrl}?q=${encodeURIComponent(query)}`);
            
            if (!response.ok) {
                throw new Error('Primary API failed');
            }
            
            const data = await response.json();
            
            // Check if response has error (like unauthorized or connection issue)
            if (data.error) {
                throw new Error(data.error);
            }
            
            this.displaySuggestions(data);
            
        } catch (error) {
            console.warn('Primary API failed, trying SQLite fallback:', error);
            this.tryFallback(query);
        }
    }
    
    async tryFallback(query) {
        try {
            // Try SQLite API as fallback
            const response = await fetch(`api/search-nomor-perkara-sqlite.php?q=${encodeURIComponent(query)}`);
            
            if (!response.ok) {
                throw new Error('SQLite API failed');
            }
            
            const data = await response.json();
            
            if (data.error) {
                throw new Error(data.error);
            }
            
            // Add indicator that this is from SQLite
            this.displaySuggestions(data, true);
            
        } catch (error) {
            console.error('Both APIs failed:', error);
            this.showError();
        }
    }
    
    showLoading() {
        this.suggestions.innerHTML = '<div class="autocomplete-loading"><i class="fa fa-spinner fa-spin"></i> Mencari...</div>';
        this.suggestions.style.display = 'block';
    }
    
    showError() {
        this.suggestions.innerHTML = '<div class="autocomplete-no-results">Terjadi kesalahan saat mencari data</div>';
        this.suggestions.style.display = 'block';
    }
    
    displaySuggestions(data, fromSQLite = false) {
        this.currentIndex = -1;
        
        if (data.length === 0) {
            this.suggestions.innerHTML = '<div class="autocomplete-no-results">Tidak ada nomor perkara yang cocok</div>';
            this.suggestions.style.display = 'block';
            return;
        }
        
        const sourceIndicator = fromSQLite ? 
            '<div class="autocomplete-source"><i class="fa fa-database"></i> Data dari SQLite lokal</div>' : 
            '<div class="autocomplete-source"><i class="fa fa-server"></i> Data dari SIPP online</div>';
        
        const html = data.map(item => {
            let content = `<div class="suggestion-main">${this.highlightMatch(item.nomor_perkara, this.input.value)}</div>`;
            
            if (this.options.showDetails) {
                const lokasi = `Ruang ${item.no_ruang || '-'}, Lemari ${item.no_lemari || '-'}, Rak ${item.no_rak || '-'}, Berkas ${item.no_berkas || '-'}`;
                content += `<div class="suggestion-detail">Arsip: ${item.nomor_arsip || '-'} | ${lokasi}</div>`;
            }
            
            return `
                <div class="autocomplete-suggestion" 
                     data-nomor="${item.nomor_perkara}" 
                     data-arsip="${item.nomor_arsip || ''}"
                     data-ruang="${item.no_ruang || ''}"
                     data-lemari="${item.no_lemari || ''}"
                     data-rak="${item.no_rak || ''}"
                     data-berkas="${item.no_berkas || ''}">
                    ${content}
                </div>
            `;
        }).join('');
        
        this.suggestions.innerHTML = sourceIndicator + html;
        this.suggestions.style.display = 'block';
        
        // Add click events
        this.suggestions.querySelectorAll('.autocomplete-suggestion').forEach(item => {
            item.addEventListener('click', () => this.selectSuggestion(item));
        });
    }
    
    highlightMatch(text, query) {
        if (!query) return text;
        const regex = new RegExp(`(${query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')})`, 'gi');
        return text.replace(regex, '<strong>$1</strong>');
    }
    
    selectSuggestion(item) {
        const selectedData = {
            nomor_perkara: item.dataset.nomor,
            nomor_arsip: item.dataset.arsip,
            no_ruang: item.dataset.ruang,
            no_lemari: item.dataset.lemari,
            no_rak: item.dataset.rak,
            no_berkas: item.dataset.berkas
        };
        
        this.input.value = selectedData.nomor_perkara;
        this.hideSuggestions();
        
        // Trigger events
        this.input.dispatchEvent(new Event('change'));
        this.input.dispatchEvent(new CustomEvent('autocomplete:select', { 
            detail: selectedData 
        }));
        
        // Call callback if provided
        if (typeof this.options.onSelect === 'function') {
            this.options.onSelect(selectedData);
        }
    }
    
    hideSuggestions() {
        this.suggestions.style.display = 'none';
        this.currentIndex = -1;
    }
    
    // Public methods
    destroy() {
        if (this.suggestions) {
            this.suggestions.remove();
        }
        clearTimeout(this.searchTimeout);
    }
    
    setValue(value) {
        this.input.value = value;
    }
    
    getValue() {
        return this.input.value;
    }
}

// Export for use in other scripts
if (typeof module !== 'undefined' && module.exports) {
    module.exports = NomorPerkaraAutocomplete;
}
