let dataTable;
let dateRangePicker;
let detailsModal;
let currentPostingId = null;

$(function () {
    // CSRF setup
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });

    // Initialize Details Modal
    detailsModal = new bootstrap.Modal(document.getElementById('detailsModal'));

    // Initialize Flatpickr date range picker
    dateRangePicker = flatpickr('#filterDateRange', {
        mode: 'range',
        dateFormat: 'Y-m-d',
        maxDate: 'today',
        onChange: function(selectedDates, dateStr, instance) {
            if (selectedDates.length === 2) {
                dataTable.ajax.reload();
            }
        }
    });

    // Initialize DataTable
    dataTable = $('#postingHistoryTable').DataTable({
        processing: true,
        serverSide: true,
        ajax: {
            url: pageData.urls.datatable,
            type: 'GET',
            data: function(d) {
                d.module = $('#filterModule').val();
                d.status = $('#filterStatus').val();
                const dates = dateRangePicker.selectedDates;
                if (dates.length === 2) {
                    d.start_date = dates[0].toISOString().split('T')[0];
                    d.end_date = dates[1].toISOString().split('T')[0];
                }
            },
            error: function(xhr) {
                console.error('DataTable error:', xhr);
                Swal.fire({
                    icon: 'error',
                    title: pageData.labels.error,
                    text: pageData.labels.genericError,
                    customClass: { confirmButton: 'btn btn-danger' },
                    buttonsStyling: false
                });
            }
        },
        columns: [
            { data: 'id', name: 'id' },
            { data: 'posted_at_formatted', name: 'posted_at' },
            { data: 'source', name: 'source_module' },
            { data: 'target', name: 'target_module' },
            { data: 'action_badge', name: 'action', orderable: false },
            { data: 'status_badge', name: 'status', orderable: false },
            { data: 'amount_formatted', name: 'amount' },
            { data: 'posted_by_name', name: 'posted_by', orderable: false },
            { data: 'actions', name: 'actions', orderable: false, searchable: false }
        ],
        order: [[1, 'desc']], // Order by posted_at descending
        pageLength: 25,
        lengthMenu: [10, 25, 50, 100],
        language: {
            search: '',
            searchPlaceholder: pageData.labels.searchPlaceholder || 'Search...',
            processing: pageData.labels.processing || 'Processing...',
            lengthMenu: pageData.labels.lengthMenu || 'Show _MENU_ entries',
            info: pageData.labels.info || 'Showing _START_ to _END_ of _TOTAL_ entries',
            infoEmpty: pageData.labels.infoEmpty || 'No entries to show',
            infoFiltered: pageData.labels.infoFiltered || '(filtered from _MAX_ total entries)',
            emptyTable: pageData.labels.emptyTable || 'No data available',
            zeroRecords: pageData.labels.zeroRecords || 'No matching records found',
            paginate: {
                first: pageData.labels.paginate?.first || 'First',
                last: pageData.labels.paginate?.last || 'Last',
                next: '<i class="bx bx-chevron-right"></i>',
                previous: '<i class="bx bx-chevron-left"></i>'
            }
        },
        dom: '<"row"<"col-sm-12 col-md-6"l><"col-sm-12 col-md-6 d-flex justify-content-end"f>>t<"row"<"col-sm-12 col-md-6"i><"col-sm-12 col-md-6"p>>'
    });

    // Filter change handlers
    $('#filterModule, #filterStatus').on('change', function() {
        dataTable.ajax.reload();
    });

    // Clear filters button
    $('#clearFilters').on('click', function() {
        $('#filterModule').val('');
        $('#filterStatus').val('');
        dateRangePicker.clear();
        dataTable.ajax.reload();
    });

    // Retry from modal button
    $('#retryFromModal').on('click', function() {
        if (currentPostingId) {
            detailsModal.hide();
            retryPosting(currentPostingId);
        }
    });
});

/**
 * View posting details
 */
function viewDetails(id) {
    currentPostingId = id;

    // Show loading state in modal
    $('#detail-source-module, #detail-source-type, #detail-source-id').text('-');
    $('#detail-target-module, #detail-target-type, #detail-target-id').text('-');
    $('#detail-action, #detail-status, #detail-amount').text('-');
    $('#detail-posted-by, #detail-posted-at, #detail-retry-count').text('-');
    $('#detail-description-section, #detail-error-section, #detail-old-values-section, #detail-new-values-section').hide();
    $('#retryFromModal').hide();

    // Show modal
    detailsModal.show();

    // Fetch details
    $.ajax({
        url: pageData.urls.viewDetails.replace(':id', id),
        type: 'GET',
        success: function(response) {
            if (response.success && response.data) {
                const data = response.data;

                // Populate source info
                $('#detail-source-module').text(data.source_module);
                $('#detail-source-type').text(data.source_entity_type);
                $('#detail-source-id').text('#' + data.source_entity_id);

                // Populate target info
                $('#detail-target-module').text(data.target_module);
                $('#detail-target-type').text(data.target_entity_type);
                $('#detail-target-id').text(data.target_entity_id ? '#' + data.target_entity_id : '-');

                // Populate general info
                $('#detail-action').text(data.action ? data.action.charAt(0).toUpperCase() + data.action.slice(1) : '-');
                $('#detail-status').html(getStatusBadge(data.status));
                $('#detail-amount').text(data.amount_formatted || '-');
                $('#detail-posted-by').text(data.posted_by);
                $('#detail-posted-at').text(data.posted_at);
                $('#detail-retry-count').text(data.retry_count || 0);

                // Description
                if (data.description) {
                    $('#detail-description').text(data.description);
                    $('#detail-description-section').show();
                }

                // Error message
                if (data.error_message) {
                    $('#detail-error-message').text(data.error_message);
                    $('#detail-error-section').show();
                }

                // Old values
                if (data.old_values && Object.keys(data.old_values).length > 0) {
                    $('#detail-old-values').text(JSON.stringify(data.old_values, null, 2));
                    $('#detail-old-values-section').show();
                }

                // New values
                if (data.new_values && Object.keys(data.new_values).length > 0) {
                    $('#detail-new-values').text(JSON.stringify(data.new_values, null, 2));
                    $('#detail-new-values-section').show();
                }

                // Show retry button if can retry
                if (data.can_retry) {
                    $('#retryFromModal').show();
                }
            }
        },
        error: function(xhr) {
            Swal.fire({
                icon: 'error',
                title: pageData.labels.error,
                text: xhr.responseJSON?.message || pageData.labels.genericError,
                customClass: { confirmButton: 'btn btn-danger' },
                buttonsStyling: false
            });
            detailsModal.hide();
        }
    });
}

/**
 * Retry a failed posting
 */
function retryPosting(id) {
    Swal.fire({
        title: pageData.labels.confirmRetry,
        text: pageData.labels.retryText,
        icon: 'warning',
        showCancelButton: true,
        confirmButtonText: pageData.labels.yesRetry,
        cancelButtonText: pageData.labels.cancel,
        customClass: {
            confirmButton: 'btn btn-warning me-3',
            cancelButton: 'btn btn-label-secondary'
        },
        buttonsStyling: false
    }).then((result) => {
        if (result.isConfirmed) {
            // Show loading
            Swal.fire({
                title: pageData.labels.processing,
                html: pageData.labels.pleaseWait,
                allowOutsideClick: false,
                allowEscapeKey: false,
                didOpen: () => {
                    Swal.showLoading();
                }
            });

            $.ajax({
                url: pageData.urls.retry.replace(':id', id),
                type: 'POST',
                success: function(response) {
                    Swal.fire({
                        icon: response.success ? 'success' : 'warning',
                        title: response.success ? pageData.labels.success : pageData.labels.error,
                        text: response.message || (response.success ? pageData.labels.retrySuccess : pageData.labels.retryError),
                        customClass: { confirmButton: response.success ? 'btn btn-success' : 'btn btn-warning' },
                        buttonsStyling: false
                    });
                    dataTable.ajax.reload();
                    refreshStatistics();
                },
                error: function(xhr) {
                    Swal.fire({
                        icon: 'error',
                        title: pageData.labels.error,
                        text: xhr.responseJSON?.message || pageData.labels.retryError,
                        customClass: { confirmButton: 'btn btn-danger' },
                        buttonsStyling: false
                    });
                }
            });
        }
    });
}

/**
 * Get status badge HTML
 */
function getStatusBadge(status) {
    const badges = {
        'success': `<span class="badge bg-label-success">${pageData.labels?.success || 'Success'}</span>`,
        'failed': `<span class="badge bg-label-danger">${pageData.labels?.failed || 'Failed'}</span>`,
        'pending': `<span class="badge bg-label-warning">${pageData.labels?.pending || 'Pending'}</span>`
    };
    return badges[status] || '<span class="badge bg-label-secondary">' + status + '</span>';
}

/**
 * Refresh statistics cards
 */
function refreshStatistics() {
    $.ajax({
        url: pageData.urls.statistics,
        type: 'GET',
        success: function(response) {
            if (response) {
                $('#stat-total').text(formatNumber(response.total || 0));
                $('#stat-successful').text(formatNumber(response.successful || 0));
                $('#stat-failed').text(formatNumber(response.failed || 0));
                $('#stat-today').text(formatNumber(response.today || 0));
            }
        }
    });
}

/**
 * Format number with thousands separator
 */
function formatNumber(num) {
    return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}

// Make functions globally accessible
window.viewDetails = viewDetails;
window.retryPosting = retryPosting;
