/**
 * Events Module
 * Listagem de eventos, filtros, paginação
 */
const Events = {
    // Paginação
    currentPage: 1,
    perPage: 50,

    /**
     * Carrega eventos com filtros
     */
    async load(page = 1) {
        this.currentPage = page;

        const eventType = document.getElementById('filter-event-type')?.value || '';
        const dateFrom = document.getElementById('filter-date-from')?.value || '';
        const dateTo = document.getElementById('filter-date-to')?.value || '';

        let url = `events&site_id=${App.currentSiteId || ''}&page=${page}&limit=${this.perPage}`;
        if (eventType) url += `&event_type=${eventType}`;
        if (dateFrom) url += `&date_from=${dateFrom}`;
        if (dateTo) url += `&date_to=${dateTo}`;

        try {
            const data = await Api.get(url);

            if (data.status === 'success') {
                const events = data.data || [];
                const pagination = data.pagination || { total: events.length, page: 1, pages: 1 };

                this.renderTable(events);
                this.updateInfo(pagination);
                this.renderPagination(pagination);

                // Carregar estatísticas PIX na primeira página
                if (page === 1) {
                    this.loadPixStats();
                }
            }
        } catch (error) {
            const infoEl = document.getElementById('events-info');
            if (infoEl) infoEl.textContent = 'Erro ao carregar eventos';
        }
    },

    /**
     * Renderiza cards de eventos
     */
    renderTable(events) {
        const container = document.getElementById('events-cards-container');

        if (!events || events.length === 0) {
            container.innerHTML = '<div class="col-12 text-center text-muted py-5"><i class="fas fa-inbox fa-3x mb-3 opacity-50"></i><p>Nenhum evento encontrado</p></div>';
            return;
        }

        container.innerHTML = events.map(e => {
            const time = e.created_at ? new Date(e.created_at).toLocaleString('pt-BR') : '-';
            const date = e.created_at ? new Date(e.created_at).toLocaleDateString('pt-BR') : '-';
            const hora = e.created_at ? new Date(e.created_at).toLocaleTimeString('pt-BR', { hour: '2-digit', minute: '2-digit', second: '2-digit' }) : '-';

            // Ícone baseado no tipo de evento
            const icons = {
                'visit': 'fa-eye',
                'page_view': 'fa-eye',
                'consulta_iniciada': 'fa-search',
                'consulta_debitos': 'fa-file-invoice-dollar',
                'debitos_view': 'fa-list-alt',
                'pix_gerado': 'fa-qrcode',
                'pix_copiado': 'fa-copy',
                'pix_generation_success': 'fa-check-circle',
                'consulta_erro': 'fa-exclamation-triangle',
                'payment_confirmed': 'fa-check-double'
            };
            const icon = icons[e.event_type] || 'fa-bolt';

            // Cor do card baseada no tipo
            const cardColors = {
                'pix_gerado': 'border-success',
                'pix_copiado': 'border-warning',
                'payment_confirmed': 'border-primary',
                'consulta_erro': 'border-danger',
                'visit': 'border-info'
            };
            const cardColor = cardColors[e.event_type] || '';

            // Metadados extras (se houver)
            let metadataHtml = '';
            let visitorBadge = '';
            if (e.metadata) {
                try {
                    const meta = typeof e.metadata === 'string' ? JSON.parse(e.metadata) : e.metadata;
                    if (meta) {
                        // Badge de tipo de visitante
                        const vType = meta.visitor_type || 'Desconhecido';
                        const vColor = vType === 'Humano' ? 'bg-success' : (vType.includes('Bot') ? 'bg-warning text-dark' : 'bg-danger');
                        visitorBadge = `<span class="badge ${vColor} ms-1">${vType}</span>`;

                        // Bloco de detalhes
                        metadataHtml = '<div class="mt-2 pt-2 border-top"><small class="text-muted d-block">';

                        if (meta.connection) {
                            const connColor = meta.connection === 'VPS/Datacenter' ? 'text-danger fw-bold' : 'text-success';
                            metadataHtml += `<span class="me-2"><strong>Conexão:</strong> <span class="${connColor}">${meta.connection}</span></span>`;
                        }

                        if (meta.isp) {
                            metadataHtml += `<span class="d-block text-truncate" title="${meta.isp}"><strong>ISP:</strong> ${meta.isp}</span>`;
                        }

                        if (meta.device || meta.browser) {
                            metadataHtml += `<span class="d-block"><strong>Dispositivo:</strong> ${meta.device || '-'} / ${meta.browser || '-'}</span>`;
                        }

                        if (meta.screen) {
                            metadataHtml += `<span class="d-block"><strong>Tela:</strong> ${meta.screen}</span>`;
                        }

                        metadataHtml += '</small></div>';
                    }
                } catch (ex) {
                    console.error("Error parsing metadata:", ex);
                }
            }

            return `
                <div class="col-md-6 col-lg-4">
                    <div class="card h-100 event-card ${cardColor}" style="border-left-width: 4px;">
                        <div class="card-body">
                            <div class="d-flex justify-content-between align-items-start mb-2">
                                <div>
                                    <span class="badge ${Format.eventBadgeClass(e.event_type)}">
                                        <i class="fas ${icon} me-1"></i>${Format.eventType(e.event_type)}
                                    </span>
                                    ${visitorBadge}
                                </div>
                                <small class="text-muted">${hora}</small>
                            </div>

                            <div class="mb-2">
                                ${(() => {
                    return `<small class="text-muted d-block fw-bold">${e.site_name || 'Site'}</small>`;
                })()}
                            </div>

                            ${e.placa ? `
                            <div class="d-flex gap-3 mb-2">
                                <div>
                                    <small class="text-muted d-block">Placa</small>
                                    <code class="fs-6 fw-bold">${e.placa}</code>
                                </div>
                                ${e.renavam ? `
                                <div>
                                    <small class="text-muted d-block">RENAVAM</small>
                                    <code style="font-size: 0.85em">${e.renavam}</code>
                                </div>
                                ` : ''}
                            </div>
                            ` : ''}

                            ${e.valor ? `
                            <div class="mb-2">
                                <small class="text-muted d-block">Valor</small>
                                <span class="fs-5 fw-bold text-success">${Format.brl(e.valor)}</span>
                            </div>
                            ` : ''}

                            <div class="d-flex justify-content-between align-items-end mt-auto pt-2 border-top">
                                <div>
                                    <small class="text-muted d-block">
                                        <i class="fas fa-map-marker-alt me-1"></i>
                                        ${e.geo_city ? `${e.geo_city}, ${e.geo_region}` : 'Localização não disponível'}
                                    </small>
                                    <small class="text-muted" style="font-size: 0.75em">${e.ip_address || '-'}</small>
                                </div>
                                <small class="text-muted">${date}</small>
                            </div>

                            ${metadataHtml}
                        </div>
                    </div>
                </div>
            `;
        }).join('');
    },

    /**
     * Atualiza informações de paginação
     */
    updateInfo(pagination) {
        document.getElementById('events-count').textContent = pagination.total;

        const startItem = ((pagination.page - 1) * this.perPage) + 1;
        const endItem = Math.min(pagination.page * this.perPage, pagination.total);

        document.getElementById('events-info').textContent = pagination.total > 0
            ? `Exibindo ${startItem}-${endItem} de ${pagination.total} eventos`
            : 'Nenhum evento encontrado';

        document.getElementById('events-page-count').textContent = `Página ${pagination.page} de ${pagination.pages}`;
    },

    /**
     * Renderiza paginação
     */
    renderPagination(pagination) {
        const container = document.getElementById('events-pagination');

        if (pagination.pages <= 1) {
            container.innerHTML = '';
            return;
        }

        let html = '';

        // Botão Anterior
        html += `<button class="btn btn-sm btn-outline-primary" onclick="Events.load(${pagination.page - 1})" ${pagination.page <= 1 ? 'disabled' : ''}>
            <i class="fas fa-chevron-left"></i> Anterior
        </button>`;

        // Números de página
        const maxVisible = 5;
        let startPage = Math.max(1, pagination.page - Math.floor(maxVisible / 2));
        let endPage = Math.min(pagination.pages, startPage + maxVisible - 1);

        if (endPage - startPage < maxVisible - 1) {
            startPage = Math.max(1, endPage - maxVisible + 1);
        }

        if (startPage > 1) {
            html += `<button class="btn btn-sm btn-outline-secondary" onclick="Events.load(1)">1</button>`;
            if (startPage > 2) html += `<span class="px-2">...</span>`;
        }

        for (let i = startPage; i <= endPage; i++) {
            const active = i === pagination.page ? 'btn-primary' : 'btn-outline-secondary';
            html += `<button class="btn btn-sm ${active}" onclick="Events.load(${i})">${i}</button>`;
        }

        if (endPage < pagination.pages) {
            if (endPage < pagination.pages - 1) html += `<span class="px-2">...</span>`;
            html += `<button class="btn btn-sm btn-outline-secondary" onclick="Events.load(${pagination.pages})">${pagination.pages}</button>`;
        }

        // Botão Próximo
        html += `<button class="btn btn-sm btn-outline-primary" onclick="Events.load(${pagination.page + 1})" ${pagination.page >= pagination.pages ? 'disabled' : ''}>
            Próximo <i class="fas fa-chevron-right"></i>
        </button>`;

        container.innerHTML = html;
    },

    /**
     * Limpa filtros e recarrega
     */
    clearFilters() {
        document.getElementById('filter-event-type').value = '';
        document.getElementById('filter-date-from').value = '';
        document.getElementById('filter-date-to').value = '';
        this.load(1);
    },

    /**
     * Carrega tipos de eventos para o filtro
     */
    async loadTypes() {
        try {
            const data = await Api.get('event-types');

            if (data.status === 'success' && data.data) {
                const select = document.getElementById('filter-event-type');
                select.innerHTML = '<option value="">Todos os tipos</option>';
                data.data.forEach(type => {
                    select.innerHTML += `<option value="${type.event_type}">${Format.eventType(type.event_type)} (${type.count})</option>`;
                });
            }
        } catch (error) {
            // Silenciar em produção
        }
    },

    /**
     * Carrega estatísticas por tipo de evento
     */
    async loadPixStats() {
        try {
            const siteFilter = App.currentSiteId || '';
            const data = await Api.get(`pix-stats&site_id=${siteFilter}`);

            if (data.status === 'success' && data.data) {
                const stats = data.data;
                this.renderStatsCards(stats);
            }
        } catch (error) {
            document.getElementById('events-stats-container').innerHTML =
                '<div class="col-12 text-center text-danger py-3"><i class="fas fa-exclamation-triangle me-2"></i>Erro ao carregar estatísticas</div>';
        }
    },

    /**
     * Renderiza cards de estatísticas por tipo de evento
     */
    renderStatsCards(stats) {
        const container = document.getElementById('events-stats-container');
        if (!container) return;

        const byType = stats.by_type || [];

        if (byType.length === 0) {
            container.innerHTML = '<div class="col-12 text-center text-muted py-3">Nenhum evento registrado</div>';
            return;
        }

        // Ícones e cores por tipo de evento
        const eventConfig = {
            'visit': { icon: 'fa-eye', color: 'info', label: 'Visitas' },
            'page_view': { icon: 'fa-eye', color: 'info', label: 'Visualizações' },
            'consulta_iniciada': { icon: 'fa-search', color: 'primary', label: 'Consultas Iniciadas' },
            'consulta_debitos': { icon: 'fa-file-invoice-dollar', color: 'secondary', label: 'Débitos Consultados' },
            'debitos_view': { icon: 'fa-list-alt', color: 'secondary', label: 'Débitos Visualizados' },
            'pix_gerado': { icon: 'fa-qrcode', color: 'success', label: 'PIX Gerados' },
            'pix_copiado': { icon: 'fa-copy', color: 'warning', label: 'PIX Copiados' },
            'pix_generation_success': { icon: 'fa-check-circle', color: 'success', label: 'PIX Sucesso' },
            'consulta_erro': { icon: 'fa-exclamation-triangle', color: 'danger', label: 'Erros de Consulta' },
            'payment_confirmed': { icon: 'fa-check-double', color: 'primary', label: 'Pagamentos Confirmados' },
            'cnpj_consulta': { icon: 'fa-building', color: 'info', label: 'Consultas CNPJ' },
            'consulta': { icon: 'fa-search', color: 'primary', label: 'Consultas' },
            'consulta_placa': { icon: 'fa-car', color: 'primary', label: 'Consultas Placa' }
        };

        // Card resumo geral primeiro
        let html = `
            <div class="col-6 col-md-4 col-lg-2">
                <div class="card h-100 border-dark stat-card-clickable" onclick="Events.filterByType('')" style="cursor: pointer;">
                    <div class="card-body text-center py-3">
                        <i class="fas fa-chart-bar fa-2x text-dark mb-2"></i>
                        <div class="fs-4 fw-bold">${stats.total_events || 0}</div>
                        <div class="small text-muted">Total Eventos</div>
                        <div class="small text-success"><strong>${stats.events_today || 0}</strong> hoje</div>
                    </div>
                </div>
            </div>
            <div class="col-6 col-md-4 col-lg-2">
                <div class="card h-100 border-success stat-card-clickable" onclick="Events.filterByType('pix_gerado')" style="cursor: pointer;">
                    <div class="card-body text-center py-3">
                        <i class="fas fa-money-bill-wave fa-2x text-success mb-2"></i>
                        <div class="fs-4 fw-bold text-success">${Format.brl(stats.total_value || 0)}</div>
                        <div class="small text-muted">Valor PIX Total</div>
                        <div class="small text-success"><strong>${Format.brl(stats.valor_hoje || 0)}</strong> hoje</div>
                    </div>
                </div>
            </div>
        `;

        // Cards por tipo de evento
        byType.forEach(item => {
            const config = eventConfig[item.event_type] || { icon: 'fa-bolt', color: 'secondary', label: item.event_type };
            const hasValue = parseFloat(item.valor_total) > 0;

            html += `
                <div class="col-6 col-md-4 col-lg-2">
                    <div class="card h-100 border-${config.color} stat-card-clickable" onclick="Events.filterByType('${item.event_type}')" style="cursor: pointer;">
                        <div class="card-body text-center py-3">
                            <i class="fas ${config.icon} fa-2x text-${config.color} mb-2"></i>
                            <div class="fs-4 fw-bold">${item.total}</div>
                            <div class="small text-muted text-truncate" title="${config.label}">${config.label}</div>
                            <div class="small text-success"><strong>${item.today}</strong> hoje</div>
                            ${hasValue ? `<div class="small text-success">${Format.brl(item.valor_total)}</div>` : ''}
                        </div>
                    </div>
                </div>
            `;
        });

        container.innerHTML = html;
    },

    /**
     * Filtra eventos por tipo (ao clicar no card de estatística)
     */
    filterByType(type) {
        const select = document.getElementById('filter-event-type');
        if (select) {
            select.value = type;
            this.load(1);
        }
    }
};
