import { updateEmailNotifications, initEmailNotificationsForm, initScrollToTopButton } from '../utils.js';

(async ($) => {
    const dataTableConfig = {
        serverSide: true,
        stateSave: true,
        retrieve: true,
        bSort: false,
        processing: true,
        language: {
            processing: '<i class="fa fa-spinner fa-spin fa-3x fa-fw"></i><span class="sr-only">Loading...</span> ',
            search: '',
            searchPlaceholder: 'Search',
        },
        pageLength: 10,
        ajax: {
            url: `${ajaxurl}?action=istkr_get_404_log`,
            type: "POST",
            data: function(d){
                d.wp_nonce = istkr_backend_data.ajax_nonce
            }
        },
        dom: 'lBfrtip',
        buttons: [
            { extend: 'csv', className: 'dt-action-button', exportOptions: { columns: ':visible' } },
            { extend: 'excel', className: 'dt-action-button', exportOptions: { columns: ':visible' } },
            { extend: 'print', className: 'dt-action-button', exportOptions: { columns: ':visible' } },
            { extend: 'colvis', postfixButtons: ['colvisRestore'], className: 'dt-action-button' },
        ],
        columns: [
            { data: 'id' },
            { data: 'path' },
            { data: 'referrer' },
            {
                data: null,
                render: function (data, type, row) {
                    return row.user_agent ? `<a href="#" class="user-agent">${row.user_agent}</a>` : 'N/A';
                }
            },
            { data: 'hits' },
            { data: 'ip' },
            { data: 'country' },
            { data: 'created_at' },
            { data: 'updated_at' },
            {
                data: null,
                render: function (data, type, row) {
                    const actions =
                        `<div class="actions">
                            <button class="btn btn-outline-success istkr_404_recheck_path" style="padding:6px 12px" title="Check availability of the URL again"  data-id="${row.id}"><i class="fa fa-solid fa-arrows-rotate" aria-hidden="true"></i></button>
                            <button class="btn btn-outline-warning istkr_404_remove_path" style="padding:6px 12px" title="Remove the URL from list" data-id="${row.id}"><i class="fa fa-solid fa-trash" aria-hidden="true"></i></button>
                        </div>`;
                    return actions;
                }
            }
        ],
        columnDefs: [
            // Id, User agent, First seen
            { targets: [0, 3, 7], visible: false },
        ],
    
    };

    $('#istkr-404-redirects-table').DataTable(dataTableConfig);

    await initEmailNotificationsForm($('#istkr_404_notifications_form'));

    $('#istkr_404_notifications_form').on('submit', async function (e) {
        e.preventDefault();
        const form = $('#istkr_404_notifications_form');
        const action = 'istkr_change_404_notifications_status';
        await updateEmailNotifications(form, action);
    });

    $('#istkr_404_clear_log').on('click', async function () {
        try {
            if (confirm('Do you really want to clear log of 404 errors?')) {

                const rawResponse = await jQuery.post(ajaxurl, {
                    action: 'istkr_404_clear_log',
                    wp_nonce: istkr_backend_data.ajax_nonce,
                });

                let response = JSON.parse(rawResponse);
                if (!response.success) {
                    throw new Error('Request error');
                }
                toastr.success('Log was cleared. Reload the page', 'Success', { timeOut: 5000 });

                $('#istkr-404-redirects-table').DataTable().ajax.reload();
            }
        } catch (error) {
            toastr.error(error, 'Error', { timeOut: 5000 });
        }
    });

    function handleTableButtonClick(action, successMessage, errorMessage) {
        return async function (e) {
            try {
                const id = $(e.currentTarget).data('id');
                if (!id) {
                    console.error(`Attribute 'data-id' not found in target element`, e.currentTarget);
                    return;
                }
                const rawResponse = await jQuery.post(ajaxurl, {
                    action,
                    id,
                    wp_nonce: istkr_backend_data.ajax_nonce,
                });
                let response = JSON.parse(rawResponse);
                if (response.success) {
                    toastr.success(successMessage, 'Success', { timeOut: 5000 });
                    $('#istkr-404-redirects-table').DataTable().ajax.reload();
                } else {
                    toastr.error(response.error || errorMessage, 'Oh no!', { timeOut: 5000 });
                }
               
               
            } catch (error) {
                toastr.error(error, 'Error', { timeOut: 5000 });
            }
        };
    }

    $('#istkr-404-redirects-table')
        .on('click', '.istkr_404_recheck_path', handleTableButtonClick('istkr_404_recheck_path', 'Everything is good now', 'The path is still unavailable on the website'))
        .on('click', '.istkr_404_remove_path', handleTableButtonClick('istkr_404_remove_path', 'Path removed from table', 'Request error'))
      
    initScrollToTopButton();

    $('table.dataTable').on('click', '.user-agent', function (e) {
        e.preventDefault();
        const uaParserInstance = UAParser( $(this).text());
        const details = $('<ul></ul>');
        $.each(uaParserInstance, function (section, info) {
            if (section === 'ua') { return; }
            const li = $('<li></li>').html(`<strong>${section.toUpperCase()}</strong>`).appendTo(details);
            const ul = $('<ul></ul').appendTo(li);
            for (const prop in uaParserInstance[section]) {
                const value =  uaParserInstance[section][prop] ?? 'N/A';
                ul.append($('<li></li>').html(`<span style="text-transform: capitalize;">${prop}: ${value}</span>`));
            }
        });
        $('.user-agent-modal .modal-body').html(details);
        new bootstrap.Modal(document.getElementsByClassName('user-agent-modal')[0]).show();
    });
})(jQuery);
