/**
 * DataTable Initialization Module
 *
 * Provides a standardized way to initialize DataTables across the application.
 *
 * Usage:
 *   import { initDataTable, initServerSideDataTable } from './modules/datatable-init';
 *
 *   // Basic usage
 *   const table = initDataTable('#customerTable');
 *
 *   // With custom options
 *   const table = initDataTable('#orderTable', {
 *       pageLength: 25,
 *       order: [[1, 'asc']]
 *   });
 *
 *   // Server-side processing
 *   const table = initServerSideDataTable('#largeTable', '/api/data', {
 *       columns: [
 *           { data: 'id' },
 *           { data: 'name' },
 *           { data: 'actions', orderable: false }
 *       ]
 *   });
 */

/**
 * Default DataTable configuration
 */
const defaultConfig = {
    dom: 'Bfrtip',
    buttons: [
        {
            extend: 'copy',
            className: 'btn btn-secondary btn-sm',
            text: '<i class="fas fa-copy"></i> Copy'
        },
        {
            extend: 'csv',
            className: 'btn btn-secondary btn-sm',
            text: '<i class="fas fa-file-csv"></i> CSV'
        },
        {
            extend: 'excel',
            className: 'btn btn-secondary btn-sm',
            text: '<i class="fas fa-file-excel"></i> Excel'
        },
        {
            extend: 'pdf',
            className: 'btn btn-secondary btn-sm',
            text: '<i class="fas fa-file-pdf"></i> PDF'
        },
        {
            extend: 'print',
            className: 'btn btn-secondary btn-sm',
            text: '<i class="fas fa-print"></i> Print'
        }
    ],
    pageLength: 10,
    lengthMenu: [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
    responsive: true,
    autoWidth: false,
    language: {
        search: "Search:",
        lengthMenu: "Show _MENU_ entries",
        info: "Showing _START_ to _END_ of _TOTAL_ entries",
        infoEmpty: "No entries available",
        infoFiltered: "(filtered from _MAX_ total entries)",
        paginate: {
            first: '<i class="fas fa-angle-double-left"></i>',
            last: '<i class="fas fa-angle-double-right"></i>',
            next: '<i class="fas fa-angle-right"></i>',
            previous: '<i class="fas fa-angle-left"></i>'
        },
        emptyTable: "No data available",
        zeroRecords: "No matching records found"
    },
    order: [[0, 'desc']]
};

/**
 * Initialize a DataTable with standard configuration
 *
 * @param {string} selector - jQuery selector for the table
 * @param {Object} options - Additional DataTable options
 * @returns {DataTable} - The DataTable instance
 */
export function initDataTable(selector, options = {}) {
    const config = { ...defaultConfig, ...options };

    // Merge button configurations if provided
    if (options.buttons === false) {
        config.dom = 'frtip';
        delete config.buttons;
    } else if (Array.isArray(options.buttons)) {
        config.buttons = options.buttons;
    }

    return $(selector).DataTable(config);
}

/**
 * Initialize a server-side DataTable
 *
 * @param {string} selector - jQuery selector for the table
 * @param {string} ajaxUrl - URL for server-side data
 * @param {Object} options - Additional DataTable options
 * @returns {DataTable} - The DataTable instance
 */
export function initServerSideDataTable(selector, ajaxUrl, options = {}) {
    const serverConfig = {
        ...defaultConfig,
        processing: true,
        serverSide: true,
        ajax: {
            url: ajaxUrl,
            type: 'GET',
            data: function(d) {
                // Add CSRF token to request
                d._token = document.querySelector('meta[name="csrf-token"]')?.content;
                return d;
            },
            error: function(xhr, error, thrown) {
                console.error('DataTable AJAX error:', error);
                if (window.toastr) {
                    toastr.error('Failed to load data. Please refresh the page.');
                }
            }
        },
        ...options
    };

    return $(selector).DataTable(serverConfig);
}

/**
 * Reload a DataTable
 *
 * @param {DataTable} table - The DataTable instance
 * @param {boolean} resetPaging - Whether to reset to first page
 */
export function reloadDataTable(table, resetPaging = false) {
    if (table && typeof table.ajax === 'object') {
        table.ajax.reload(null, resetPaging);
    } else if (table) {
        table.draw(resetPaging);
    }
}

/**
 * Destroy a DataTable and restore the original table
 *
 * @param {string} selector - jQuery selector for the table
 */
export function destroyDataTable(selector) {
    if ($.fn.DataTable.isDataTable(selector)) {
        $(selector).DataTable().destroy();
    }
}

export default {
    initDataTable,
    initServerSideDataTable,
    reloadDataTable,
    destroyDataTable
};
