import 'bootstrap';
import $ from 'jquery';
import 'datatables.net-bs5';

function destroyDataTable(selector: string): void {
    if ($.fn.DataTable.isDataTable(selector)) {
        $(selector).DataTable().destroy();
    }
}

function getLang(): string {
    if (window.location.href.indexOf('/de/') > -1) {
        return 'de';
    }
    if (window.location.href.indexOf('/en/') > -1) {
        return 'en';
    }
    if (window.location.href.indexOf('/es/') > -1) {
        return 'es';
    }
    if (window.location.href.indexOf('/ru/') > -1) {
        return 'ru';
    }
    return 'de';
}

let deleteUserId: string | number;

export function initLicenseTable(): void {
    destroyDataTable('#licenseTable');

    $('#licenseTable').DataTable({
        initComplete: function () {
            $('input[type="search"]').first().focus();
        },
        stateSave: true,
        autoWidth: true,
        paging: true,
        ordering: true,
        order: [[0, 'desc']],
        language: {
            search: '',
            searchPlaceholder: 'Search',
        },
        lengthMenu: [[5, 10, 25, 50, -1], [5, 10, 25, 50, 100]],
        pageLength: 5,
        dom: '<"table-header-container"<"show-entire-custom"l><"search-section-custom"f>>rt<"table-footer-container"<"show-entire-custom"i><"pages-section-custom"p>>',
    });
}

if (document.getElementById('licenseTable') && !document.getElementById('admDashboardOffcanvasContent')) {
    $(function () {
        initLicenseTable();
    });
}

$(document).on('click', '.button-delete-ts', function () {
    deleteUserId = $(this).data('id');
});

$(document).on('click', '#confirmDeleteBtn', function () {
    if (deleteUserId) {
        const deleteUrl = `/adm/${getLang()}/license/remove/${deleteUserId}`;
        window.location.href = deleteUrl;
    } else {
        console.error('No user ID set for deletion');
    }
});
