/**
 * Fusion Authorizer Portal - Real-time Search
 */

odoo.define('fusion_authorizer_portal.portal_search', function (require) {
    'use strict';
    
    var publicWidget = require('web.public.widget');
    var ajax = require('web.ajax');
    
    publicWidget.registry.PortalSearch = publicWidget.Widget.extend({
        selector: '#portal-search-input',
        events: {
            'input': '_onSearchInput',
            'keydown': '_onKeyDown',
        },
        
        init: function () {
            this._super.apply(this, arguments);
            this.debounceTimer = null;
            this.searchEndpoint = this._getSearchEndpoint();
            this.resultsContainer = null;
        },
        
        start: function () {
            this._super.apply(this, arguments);
            this.resultsContainer = document.getElementById('cases-table-body');
            return Promise.resolve();
        },
        
        _getSearchEndpoint: function () {
            // Determine which portal we're on
            var path = window.location.pathname;
            if (path.includes('/my/authorizer')) {
                return '/my/authorizer/cases/search';
            } else if (path.includes('/my/sales')) {
                return '/my/sales/cases/search';
            }
            return null;
        },
        
        _onSearchInput: function (ev) {
            var self = this;
            var query = ev.target.value.trim();
            
            clearTimeout(this.debounceTimer);
            
            if (query.length < 2) {
                // If query is too short, reload original page
                return;
            }
            
            // Debounce - wait 250ms before searching
            this.debounceTimer = setTimeout(function () {
                self._performSearch(query);
            }, 250);
        },
        
        _onKeyDown: function (ev) {
            if (ev.key === 'Enter') {
                ev.preventDefault();
                var query = ev.target.value.trim();
                if (query.length >= 2) {
                    this._performSearch(query);
                }
            } else if (ev.key === 'Escape') {
                ev.target.value = '';
                window.location.reload();
            }
        },
        
        _performSearch: function (query) {
            var self = this;
            
            if (!this.searchEndpoint) {
                console.error('Search endpoint not found');
                return;
            }
            
            // Show loading indicator
            this._showLoading(true);
            
            ajax.jsonRpc(this.searchEndpoint, 'call', {
                query: query
            }).then(function (response) {
                self._showLoading(false);
                
                if (response.error) {
                    console.error('Search error:', response.error);
                    return;
                }
                
                self._renderResults(response.results, query);
            }).catch(function (error) {
                self._showLoading(false);
                console.error('Search failed:', error);
            });
        },
        
        _showLoading: function (show) {
            var spinner = document.querySelector('.search-loading');
            if (spinner) {
                spinner.classList.toggle('active', show);
            }
        },
        
        _renderResults: function (results, query) {
            if (!this.resultsContainer) {
                return;
            }
            
            if (!results || results.length === 0) {
                this.resultsContainer.innerHTML = `
                    <tr>
                        <td colspan="6" class="text-center py-4">
                            <i class="fa fa-search fa-2x text-muted mb-2"></i>
                            <p class="text-muted mb-0">No results found for "${query}"</p>
                        </td>
                    </tr>
                `;
                return;
            }
            
            var html = '';
            var isAuthorizer = window.location.pathname.includes('/my/authorizer');
            var baseUrl = isAuthorizer ? '/my/authorizer/case/' : '/my/sales/case/';
            
            results.forEach(function (order) {
                var stateClass = 'bg-secondary';
                if (order.state === 'sent') stateClass = 'bg-primary';
                else if (order.state === 'sale') stateClass = 'bg-success';
                
                html += `
                    <tr class="search-result-row">
                        <td>${self._highlightMatch(order.name, query)}</td>
                        <td>${self._highlightMatch(order.partner_name, query)}</td>
                        <td>${order.date_order}</td>
                        <td>${self._highlightMatch(order.claim_number || '-', query)}</td>
                        <td><span class="badge ${stateClass}">${order.state_display}</span></td>
                        <td>
                            <a href="${baseUrl}${order.id}" class="btn btn-sm btn-primary">
                                <i class="fa fa-eye me-1"></i>View
                            </a>
                        </td>
                    </tr>
                `;
            });
            
            this.resultsContainer.innerHTML = html;
        },
        
        _highlightMatch: function (text, query) {
            if (!text || !query) return text || '';
            
            var regex = new RegExp('(' + query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + ')', 'gi');
            return text.replace(regex, '<span class="search-highlight">$1</span>');
        }
    });
    
    return publicWidget.registry.PortalSearch;
});
