/**
 * CloudXM NFe Invoices Page JavaScript
 */

(function($) {
    'use strict';

    var currentPage = 1;
    var currentFilters = {};

    function extractResponseMessage(response, fallback) {
        if (response && response.data) {
            if (typeof response.data === 'string') {
                return response.data;
            }
            if (response.data.message) {
                return response.data.message;
            }
        }
        if (response && response.message) {
            return response.message;
        }
        return fallback || '';
    }

    function extractErrorFromXhr(xhr, fallback) {
        if (xhr && xhr.responseJSON) {
            return extractResponseMessage(xhr.responseJSON, fallback);
        }
        if (xhr && xhr.responseText) {
            try {
                var parsed = JSON.parse(xhr.responseText);
                return extractResponseMessage(parsed, fallback);
            } catch(e) {}
        }
        return fallback;
    }

    function init() {
        bindInvoiceRowHandlers();
        loadInvoices();
    }

    $('#apply-filters').on('click', function() {
        currentFilters = {
            year: $('#filter_year').val(),
            start_date: $('#filter_start_date').val(),
            end_date: $('#filter_end_date').val(),
            status: $('#filter_status').val()
        };
        currentPage = 1;
        loadInvoices();
    });

    $('#clear-filters').on('click', function() {
        $('#nfe-filters-form')[0].reset();
        currentFilters = {};
        currentPage = 1;
        loadInvoices();
    });

    $('#select-all-invoices').on('change', function() {
        $('#nfe-invoices-body input[type="checkbox"]').prop('checked', $(this).prop('checked'));
    });

    $('#apply-bulk-action').on('click', function() {
        var action = $('#bulk-action-selector').val();
        if (!action) return;

        var selectedInvoices = $('#nfe-invoices-body input[type="checkbox"]:checked');

        if (selectedInvoices.length === 0) {
            getBulkIdsAndConfirm(action);
        } else {
            var ids = selectedInvoices.map(function() {
                return $(this).val();
            }).get();
            processBulkDownload(action, ids);
        }
    });

    function getBulkIdsAndConfirm(action) {
        var filters = {
            year: $('#filter_year').val(),
            start_date: $('#filter_start_date').val(),
            end_date: $('#filter_end_date').val()
        };

        $.ajax({
            url: cloudxm_nfe_invoices.ajax_url,
            type: 'POST',
            data: {
                action: 'nfe_get_bulk_ids',
                nonce: cloudxm_nfe_invoices.nonce,
                year: filters.year,
                start_date: filters.start_date,
                end_date: filters.end_date
            },
            success: function(response) {
                if (response.success) {
                    var count = response.data.count;

                    if (count === 0) {
                        alert(cloudxm_nfe_invoices.i18n.no_invoices);
                        return;
                    }

                    if (count > 50) {
                        var message = cloudxm_nfe_invoices.i18n.bulk_warning.replace('%d', count);
                        if (!confirm(message)) {
                            return;
                        }
                    }

                    processBulkDownload(action, []);
                } else {
                    alert(extractResponseMessage(response, cloudxm_nfe_invoices.i18n.error_getting_ids));
                }
            },
            error: function() {
                alert(cloudxm_nfe_invoices.i18n.network_error);
            }
        });
    }

    function loadInvoices() {
        $('#nfe-loading').show();
        $('#nfe-empty').hide();
        $('#nfe-error-notice').hide();

        var data = {
            action: cloudxm_nfe_invoices.action_list,
            nonce: cloudxm_nfe_invoices.nonce,
            page: currentPage
        };
        $.extend(data, currentFilters);

        $.ajax({
            url: cloudxm_nfe_invoices.ajax_url,
            type: 'POST',
            data: data,
            success: function(response) {
                $('#nfe-loading').hide();

                if (response.success) {
                    renderInvoices(response.data.invoices);
                    renderPagination(response.data.pagination);
                } else {
                    showErrorNotice(extractResponseMessage(response, cloudxm_nfe_invoices.i18n.error_loading));
                }
            },
            error: function(xhr) {
                $('#nfe-loading').hide();
                showErrorNotice(extractErrorFromXhr(xhr, cloudxm_nfe_invoices.i18n.network_error_local));
            }
        });
    }

    function renderInvoices(invoices) {
        if (!invoices || invoices.length === 0) {
            $('#nfe-empty').show();
            $('#nfe-invoices-body').empty();
            return;
        }

        $('#nfe-empty').hide();

        var html = '';
        invoices.forEach(function(invoice) {
            html += '<tr>';
            html += '<th class="check-column"><input type="checkbox" value="' + invoice.id + '"></th>';
            html += '<td>' + (invoice.display_number || cloudxm_nfe_invoices.i18n.not_issued_yet || '-') + '</td>';
            html += '<td><a href="' + invoice.order_url + '" target="_blank">#' + invoice.order_id + '</a></td>';
            html += '<td>' + invoice.emission_date_formatted + '</td>';
            html += '<td>' + (invoice.value || '-') + '</td>';
            html += '<td><span class="nfe-status-badge nfe-status-' + (invoice.status || '') + '">' + (invoice.status_label || (invoice.status ? invoice.status.charAt(0).toUpperCase() + invoice.status.slice(1) : '-')) + '</span></td>';
            html += '<td><span class="nfe-env-badge nfe-env-' + (invoice.environment || '') + '">' + (invoice.environment_label || (invoice.environment ? invoice.environment.toUpperCase() : '-')) + '</span></td>';
            html += '<td>';
            if (invoice.xml_exists) {
                html += '<span class="dashicons dashicons-media-document" title="XML Available"></span> ';
            }
            if (invoice.pdf_exists) {
                html += '<span class="dashicons dashicons-pdf" title="PDF Available"></span>';
            }
            html += '</td>';
            html += '<td>';
            html += '<button type="button" class="button button-small nfe-details-btn" data-id="' + invoice.id + '" title="' + cloudxm_nfe_invoices.i18n.view_details + '">';
            html += '<span class="dashicons dashicons-visibility"></span>';
            html += '</button>';
            html += '</td>';
            html += '<td>';
            html += '<div style="display: flex; gap: 5px; flex-wrap: wrap;">';

            // Get allowed actions
            var allowedActions = invoice.allowed_actions || [];

            // Add scheduled invoice action buttons
            if (allowedActions.includes('issue')) {
                html += '<button type="button" class="button button-small button-primary nfe-action-issue" data-id="' + invoice.id + '" title="' + cloudxm_nfe_invoices.i18n.issue_now + '">';
                html += '<span class="dashicons dashicons-media-default"></span> ' + cloudxm_nfe_invoices.i18n.issue_now;
                html += '</button> ';
            }

            if (allowedActions.includes('reschedule')) {
                html += '<button type="button" class="button button-small nfe-action-reschedule" data-id="' + invoice.id + '" title="' + cloudxm_nfe_invoices.i18n.reschedule + '">';
                html += '<span class="dashicons dashicons-calendar-alt"></span> ' + cloudxm_nfe_invoices.i18n.reschedule;
                html += '</button> ';
            }

            if (allowedActions.includes('cancel')) {
                var cancelLabel = invoice.is_scheduled
                    ? (cloudxm_nfe_invoices.i18n.cancel_schedule || cloudxm_nfe_invoices.i18n.cancel_invoice)
                    : cloudxm_nfe_invoices.i18n.cancel_invoice;
                html += '<button type="button" class="button button-small nfe-action-cancel" data-id="' + invoice.id + '" title="' + cancelLabel + '">';
                html += '<span class="dashicons dashicons-dismiss"></span> ' + cancelLabel;
                html += '</button> ';
            }

            // Keep existing download buttons for issued invoices
            if (invoice.xml_exists) {
                html += '<button type="button" class="button button-small nfe-download-btn" data-id="' + invoice.id + '" data-type="xml">';
                html += cloudxm_nfe_invoices.i18n.xml;
                html += '</button> ';
            }
            if (invoice.pdf_exists) {
                html += '<button type="button" class="button button-small nfe-download-btn" data-id="' + invoice.id + '" data-type="pdf">';
                html += cloudxm_nfe_invoices.i18n.pdf;
                html += '</button>';
            }

            html += '</div>';
            html += '</td>';
            html += '</tr>';
        });

        $('#nfe-invoices-body').html(html);

        bindInvoiceRowHandlers();
    }

    function renderPagination(pagination) {
        if (!pagination || pagination.total_pages <= 1) {
            $('#nfe-pagination').hide();
            return;
        }

        $('#nfe-pagination').show();

        var itemLabel = pagination.total_items === 1 ? cloudxm_nfe_invoices.i18n.item : cloudxm_nfe_invoices.i18n.items;
        var html = '<span class="displaying-num">' + pagination.total_items + ' ' + itemLabel + '</span>';

        html += '<span class="pagination-links">';

        if (pagination.current_page > 1) {
            html += '<button type="button" class="button page-numbers" data-page="1">&laquo;</button> ';
            html += '<button type="button" class="button page-numbers" data-page="' + (pagination.current_page - 1) + '">&lsaquo;</button> ';
        }

        var startPage = Math.max(1, pagination.current_page - 2);
        var endPage = Math.min(pagination.total_pages, pagination.current_page + 2);

        for (var i = startPage; i <= endPage; i++) {
            var activeClass = i === pagination.current_page ? 'current' : '';
            html += '<button type="button" class="button page-numbers ' + activeClass + '" data-page="' + i + '">' + i + '</button> ';
        }

        if (pagination.current_page < pagination.total_pages) {
            html += '<button type="button" class="button page-numbers" data-page="' + (pagination.current_page + 1) + '">&rsaquo;</button> ';
            html += '<button type="button" class="button page-numbers" data-page="' + pagination.total_pages + '">&raquo;</button>';
        }

        html += '</span>';

        $('#nfe-pagination .tablenav-pages').html(html);

        $('.page-numbers').on('click', function() {
            currentPage = $(this).data('page');
            loadInvoices();
        });
    }

    function showDetailsModal(id) {
        $('#nfe-details-modal').show();
        $('#nfe-details-content').html('<div class="nfe-details-loading" style="text-align: center; padding: 40px;">' +
            '<span class="spinner is-active" style="float: none;"></span>' +
            '<p>' + cloudxm_nfe_invoices.i18n.loading_details + '</p>' +
            '</div>');

        $.ajax({
            url: cloudxm_nfe_invoices.ajax_url,
            type: 'POST',
            data: {
                action: 'nfe_get_emission_details',
                nonce: cloudxm_nfe_invoices.nonce,
                id: id
            },
            success: function(response) {
                if (response.success) {
                    renderDetails(response.data.details);
                } else {
                    $('#nfe-details-content').html('<p class="error">' +
                        extractResponseMessage(response, cloudxm_nfe_invoices.i18n.failed_details) +
                        '</p>');
                }
            },
            error: function() {
                $('#nfe-details-content').html('<p class="error">' + cloudxm_nfe_invoices.i18n.network_error_simple + '</p>');
            }
        });
    }

    function renderDetails(details) {
        var i = cloudxm_nfe_invoices.i18n;
        var html = '<table class="widefat fixed striped">';

        html += '<tr><th>' + i.order + '</th><td><a href="' + details.order_url + '" target="_blank">#' + details.order_id + '</a></td></tr>';
        if (details.has_issued_document) {
            html += '<tr><th>' + i.nfe_number + '</th><td>' + (details.invoice_number || '-') + '</td></tr>';
            html += '<tr><th>' + i.access_key + '</th><td>' + (details.access_key || '-') + '</td></tr>';
            html += '<tr><th>' + i.protocol + '</th><td>' + (details.protocol || '-') + '</td></tr>';
        }
        html += '<tr><th>' + i.status + '</th><td>' + (details.status_label || details.status || '-') + '</td></tr>';
        html += '<tr><th>' + i.environment + '</th><td>' + (details.environment || '-') + '</td></tr>';
        html += '<tr><th>' + i.total_value + '</th><td>' + (details.total_value || '-') + '</td></tr>';

        if (details.has_issued_document) {
            html += '<tr><th>' + i.icms_value + '</th><td>' + (details.icms_value || '-') + '</td></tr>';
            html += '<tr><th>' + i.icms_rate + '</th><td>' + (details.icms_rate || '-') + '</td></tr>';
        }

        // Use dynamic date label from backend (Emission Date or Scheduled Date)
        var dateLabel = details.date_label || i.emission_date;
        html += '<tr><th>' + dateLabel + '</th><td>' + details.emission_date + '</td></tr>';

        // For scheduled lifecycle records, show timezone when the schedule exists.
        if ((details.is_scheduled || details.is_cancelled_scheduled) && details.scheduled_for !== '-') {
            html += '<tr><th>' + (i.scheduled_timezone || 'Timezone') + '</th><td>' + (details.scheduled_timezone || '-') + '</td></tr>';
        }

        if (details.cancellation_date && details.cancellation_date !== '-') {
            html += '<tr><th>' + i.cancellation_date + '</th><td>' + details.cancellation_date + '</td></tr>';
            html += '<tr><th>' + i.cancellation_reason + '</th><td>' + (details.cancellation_reason || '-') + '</td></tr>';
            if (details.has_issued_document) {
                html += '<tr><th>' + i.cancellation_protocol + '</th><td>' + (details.cancellation_protocol || '-') + '</td></tr>';
            }
        }

        if (details.is_pre_issue_failure && details.error_message) {
            html += '<tr><th>' + (i.error_message || 'Error Message') + '</th><td>' + details.error_message + '</td></tr>';
        }

        html += '</table>';

        $('#nfe-details-content').html(html);
    }

    function downloadFile(id, type) {
        var form = $('<form>', {
            'method': 'POST',
            'action': cloudxm_nfe_invoices.ajax_url
        });

        form.append($('<input>', { 'type': 'hidden', 'name': 'action', 'value': cloudxm_nfe_invoices.action_download }));
        form.append($('<input>', { 'type': 'hidden', 'name': 'nonce', 'value': cloudxm_nfe_invoices.nonce }));
        form.append($('<input>', { 'type': 'hidden', 'name': 'id', 'value': id }));
        form.append($('<input>', { 'type': 'hidden', 'name': 'type', 'value': type }));

        form.appendTo('body').submit().remove();
    }

    function processBulkDownload(action, ids) {
        $('#bulk-progress').show();

        var form = $('<form>', {
            'method': 'POST',
            'action': cloudxm_nfe_invoices.ajax_url
        });

        form.append($('<input>', { 'type': 'hidden', 'name': 'action', 'value': cloudxm_nfe_invoices.action_bulk_download }));
        form.append($('<input>', { 'type': 'hidden', 'name': 'nonce', 'value': cloudxm_nfe_invoices.nonce }));
        form.append($('<input>', { 'type': 'hidden', 'name': 'bulk_action', 'value': action }));
        form.append($('<input>', { 'type': 'hidden', 'name': 'ids', 'value': ids.join(',') }));

        if (ids.length === 0) {
            form.append($('<input>', { 'type': 'hidden', 'name': 'year', 'value': currentFilters.year || '' }));
            form.append($('<input>', { 'type': 'hidden', 'name': 'start_date', 'value': currentFilters.start_date || '' }));
            form.append($('<input>', { 'type': 'hidden', 'name': 'end_date', 'value': currentFilters.end_date || '' }));
        }

        form.appendTo('body').submit();
    }

    function showErrorNotice(message) {
        $('#nfe-error-notice-message').text(message);
        $('#nfe-error-notice').show();
    }

    function bindInvoiceRowHandlers() {
        $('.nfe-details-btn').off('click').on('click', function() {
            var id = $(this).data('id');
            showDetailsModal(id);
        });

        $('.nfe-download-btn').off('click').on('click', function() {
            var id = $(this).data('id');
            var type = $(this).data('type');
            downloadFile(id, type);
        });
    }

    // Issue scheduled invoice immediately
    $(document).on('click', '.nfe-action-issue', function(e) {
        e.preventDefault();
        var invoiceId = $(this).data('id');
        var $button = $(this);

        if (!confirm(cloudxm_nfe_invoices.i18n.confirm_issue)) {
            return;
        }

        $button.prop('disabled', true).text(cloudxm_nfe_invoices.i18n.processing);

        $.ajax({
            url: cloudxm_nfe_invoices.ajax_url,
            type: 'POST',
            data: {
                action: 'nfe_issue_scheduled',
                nonce: cloudxm_nfe_invoices.nonce,
                invoice_id: invoiceId
            },
            success: function(response) {
                if (response.success) {
                    alert(extractResponseMessage(response));
                    loadInvoices();
                } else {
                    alert(extractResponseMessage(response, cloudxm_nfe_invoices.i18n.error));
                }
            },
            error: function(xhr) {
                alert(extractErrorFromXhr(xhr, cloudxm_nfe_invoices.i18n.network_error));
            },
            complete: function() {
                $button.prop('disabled', false).html('<span class="dashicons dashicons-media-default"></span> ' + cloudxm_nfe_invoices.i18n.issue_now);
            }
        });
    });

    // Reschedule invoice
    $(document).on('click', '.nfe-action-reschedule', function(e) {
        e.preventDefault();
        var invoiceId = $(this).data('id');

        // Get invoice data from the table row
        var $row = $(this).closest('tr');
        var scheduledForLocal = $row.find('td:eq(3)').text().trim(); // Emission date column

        // Populate modal with current values
        $('#reschedule-invoice-id').val(invoiceId);
        $('#reschedule-datetime').val(scheduledForLocal !== '-' ? scheduledForLocal : '');
        $('#reschedule-timezone').val('America/Sao_Paulo');
        $('#reschedule-reason').val('');

        // Show modal
        $('#nfe-reschedule-modal').fadeIn(200);
    });

    // Cancel invoice
    $(document).on('click', '.nfe-action-cancel', function(e) {
        e.preventDefault();
        var invoiceId = $(this).data('id');

        // Populate modal
        $('#cancel-invoice-id').val(invoiceId);
        $('#cancel-reason').val('');

        // Show modal
        $('#nfe-cancel-modal').fadeIn(200);
    });

    // Handle reschedule form submission
    $('#nfe-reschedule-form').on('submit', function(e) {
        e.preventDefault();

        var invoiceId = $('#reschedule-invoice-id').val();
        var scheduledAt = $('#reschedule-datetime').val();
        var timezone = $('#reschedule-timezone').val();
        var reason = $('#reschedule-reason').val();

        if (!scheduledAt) {
            alert(cloudxm_nfe_invoices.i18n.datetime_required);
            return;
        }

        $.ajax({
            url: cloudxm_nfe_invoices.ajax_url,
            type: 'POST',
            data: {
                action: 'nfe_reschedule_invoice',
                nonce: cloudxm_nfe_invoices.nonce,
                invoice_id: invoiceId,
                scheduled_at: scheduledAt,
                timezone: timezone,
                scheduling_reason: reason
            },
            success: function(response) {
                if (response.success) {
                    $('#nfe-reschedule-modal').fadeOut(200);
                    alert(extractResponseMessage(response));
                    loadInvoices();
                } else {
                    alert(extractResponseMessage(response, cloudxm_nfe_invoices.i18n.error));
                }
            },
            error: function(xhr) {
                alert(extractErrorFromXhr(xhr, cloudxm_nfe_invoices.i18n.network_error));
            }
        });
    });

    // Handle cancel form submission
    $('#nfe-cancel-form').on('submit', function(e) {
        e.preventDefault();

        var invoiceId = $('#cancel-invoice-id').val();
        var reason = $('#cancel-reason').val();

        if (!reason) {
            alert(cloudxm_nfe_invoices.i18n.reason_required);
            return;
        }

        $.ajax({
            url: cloudxm_nfe_invoices.ajax_url,
            type: 'POST',
            data: {
                action: 'nfe_cancel_invoice',
                nonce: cloudxm_nfe_invoices.nonce,
                invoice_id: invoiceId,
                reason: reason
            },
            success: function(response) {
                if (response.success) {
                    $('#nfe-cancel-modal').fadeOut(200);
                    alert(extractResponseMessage(response));
                    loadInvoices();
                } else {
                    alert(extractResponseMessage(response, cloudxm_nfe_invoices.i18n.error));
                }
            },
            error: function(xhr) {
                alert(extractErrorFromXhr(xhr, cloudxm_nfe_invoices.i18n.network_error));
            }
        });
    });

    // Close modals
    $('.nfe-modal-close, .nfe-modal-overlay').on('click', function() {
        $('.nfe-modal').fadeOut(200);
    });

    $('.nfe-modal-close').on('click', function() {
        $('#nfe-details-modal').hide();
    });

    $('.nfe-modal-overlay').on('click', function() {
        $('#nfe-details-modal').hide();
    });

    $(document).ready(init);

})(jQuery);
