document.getElementById('reset-filter').addEventListener('click', function(){
    categoryChoices.removeActiveItems();
    currencyChoices.removeActiveItems();
    
    const event = new Event('change', { bubbles: true });

    document.getElementById('orderby').value = 'ID';
    document.getElementById('sort_by').value = 'desc';
    document.getElementById('keyword').value = '';
    document.getElementById('keyword').dispatchEvent(event);
});

let formipay_table_grid = new gridjs.Grid({
    server: {
        url: formipay_forms_page.ajax_url+'?action=formipay-tabledata-forms&post_status='+document.getElementById('post_status').value+'&orderby='+document.getElementById('orderby').value+'&sort='+document.getElementById('sort_by').value+'&search='+document.getElementById('keyword').value+'&_wpnonce='+formipay_forms_page.nonce,
        then: data => {
            
            if(data.posts_report){
                processPostsReport(data.posts_report);
            }

            return data.results.map(
                form => [form.ID, form.ID, form.title, form.date, form.status]
            );
        },
        total: data => data.total
    },
    columns: [
        {
            id: 'checkbox',
            name: gridjs.html(`<input type="checkbox" id="select-all-rows">`),
            width: '50px',
            formatter: (_, row) => gridjs.html(
                `<input type="checkbox" class="formipay-row-checkbox" data-id="${row.cells[0].data}">`
            )
        },
        {
            name: formipay_forms_page.columns.id,
            width: '75px'
        },
        {
            name: formipay_forms_page.columns.title,
            formatter: (_, row) => gridjs.html(`
                <b>${_}</b><br>
                <span class="post-action" style="visibility: hidden;">
                <a href="${formipay_forms_page.site_url}/wp-admin/post.php?post=${row.cells[0].data}&action=edit&_wpnonce=${formipay_forms_page.nonce}">edit</a> | <a href="#" class="delete-form" data-id="${row.cells[0].data}">delete</a> | <a href="#" class="duplicate-form" data-id="${row.cells[0].data}">duplicate</a>
                </span>
            `)
        },
        {
            name: formipay_forms_page.columns.date,
            formatter: (_, row) => gridjs.html('<span style="text-wrap: nowrap;">' + _.split(' ').join('</span><br><span style="font-size: smaller;">') + '</span>')
        },
        {
            name: formipay_forms_page.columns.status,
            formatter: (_, row) => gridjs.html(`
                <span class="status-label ${_}">${_}</span>
            `)
        },
        {
            name: formipay_forms_page.columns.shortcode,
            formatter: (_, row) => gridjs.html(`
                <input class="formipay-form-shortcode" value="[formipay form=${row.cells[0].data}]" disabled>
                <button class="copy-shortcode" data-copy="[formipay form=${row.cells[0].data}]">
                    <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24">
                        <path fill="#b7b7b7" d="M9 18q-.825 0-1.412-.587T7 16V4q0-.825.588-1.412T9 2h9q.825 0 1.413.588T20 4v12q0 .825-.587 1.413T18 18zm0-2h9V4H9zm-4 6q-.825 0-1.412-.587T3 20V6h2v14h11v2zm4-6V4z" />
                    </svg> ${formipay_forms_page.toast.copy_button.copy}
                </button>
            `)
        },
    ],
    pagination: {
        limit: 10,
        server: {
            url: (prev, page, limit) => `${prev}&limit=${limit}&offset=${page * limit}`
        },
        summary: false
    },
    className: {
        table: 'formipay-grid-table'
    }
}).render(document.getElementById('formipay-forms'));

document.addEventListener('click', function (e) {
    const copyButton = e.target.closest('[data-copy]'); // Check if the clicked element or its parent has the data-copy attribute
    if (copyButton) {
        const textToCopy = copyButton.getAttribute('data-copy');
        
        // Use the Clipboard API to copy text
        navigator.clipboard.writeText(textToCopy)
            .then(() => {
                // Optionally, display a success message
                copyButton.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24">
                                            <path fill="#000" d="m9.55 18l-5.7-5.7l1.425-1.425L9.55 15.15l9.175-9.175L20.15 7.4z" />
                                        </svg> ${formipay_forms_page.toast.copy_button.copied}`;
                setTimeout(() => {
                    copyButton.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24">
                                                <path fill="#b7b7b7" d="M9 18q-.825 0-1.412-.587T7 16V4q0-.825.588-1.412T9 2h9q.825 0 1.413.588T20 4v12q0 .825-.587 1.413T18 18zm0-2h9V4H9zm-4 6q-.825 0-1.412-.587T3 20V6h2v14h11v2zm4-6V4z" />
                                            </svg> ${formipay_forms_page.toast.copy_button.copy}`; // Reset button text
                }, 2000);

                Swal.fire({
                    icon: 'success',
                    title: formipay_forms_page.toast.copy_button.title,
                    toast: true,
                    position: "top-end",
                    showConfirmButton: false,
                    timer: 3000,
                    timerProgressBar: true,
                    customClass: {
                        container: 'top-40'
                    },
                    didOpen: (toast) => {
                        toast.onmouseenter = Swal.stopTimer;
                        toast.onmouseleave = Swal.resumeTimer;
                    }
                })
            })
            .catch((err) => {
                console.error('Failed to copy text: ', err);
            });
    }
});

jQuery(function($){

    var $deleteBtn = $('#formipay-delete-selected');

    function updateDeleteButtonVisibility() {
        if ($(document).find('.formipay-row-checkbox:checked').length > 0) {
            $deleteBtn.show();
        } else {
            $deleteBtn.hide();
        }
    }

    // Handle row and "select all" checkbox changes
    $(document).on('change', '.formipay-row-checkbox', function() {
        updateDeleteButtonVisibility();
    });

    // Handle row and "select all" checkbox changes
    $(document).on('change', '#select-all-rows', function() {
        const is_checked = $(this).is(':checked');
        $(document).find('.formipay-row-checkbox').prop('checked', is_checked);
        updateDeleteButtonVisibility();
    });

    // Handle delete button click
    $deleteBtn.on('click', function() {
        var selectedIds = $(document).find('.formipay-row-checkbox:checked').map(function() {
            return $(this).data('id');
        }).get();

        console.log(selectedIds);

        if (selectedIds.length > 0) {
            Swal.fire({
                icon: 'info',
                html: formipay_forms_page.modal.bulk_delete.question,
                showCancelButton: true,
                confirmButtonText: formipay_forms_page.modal.bulk_delete.confirmButton,
                cancelButtonText: formipay_forms_page.modal.bulk_delete.cancelButton
            }).then((result) => {
                /* Read more about isConfirmed, isDenied below */
                if (result.isConfirmed) {
                    $.ajax({
                        type: 'post',
                        url: formipay_forms_page.ajax_url,
                        data: {
                            action: 'formipay-bulk-delete-form',
                            ids: selectedIds,
                            _wpnonce: formipay_forms_page.nonce
                        },
                        success: function (res) {
                            Swal.fire({
                                title: res.data.title,
                                html: res.data.message,
                                icon: res.data.icon
                            });
                            formipay_table_grid.forceRender();
                            $(document).find('.formipay-row-checkbox').prop('checked', false);
                            updateDeleteButtonVisibility();
                            refresh_table_with_filter();
                        }
                    });
                }
            });
        }
    });

    function refresh_table_with_filter() {
        formipay_table_grid.updateConfig({
            server: {
                url: formipay_forms_page.ajax_url+'?action=formipay-tabledata-forms&post_status='+document.getElementById('post_status').value+'&orderby='+document.getElementById('orderby').value+'&sort='+document.getElementById('sort_by').value+'&search='+document.getElementById('keyword').value+'&_wpnonce='+formipay_forms_page.nonce,
                then: data => data.results.map(
                    form => [form.ID, form.ID, form.title, form.date, form.status]
                ),
                total: data => data.total
            }
        }).forceRender();
    }

    $('.form-tool, #post_status').on('change', function(){
        refresh_table_with_filter();
    });

    $(document).on('mouseover', 'td[data-column-id=title]', function(){
        $(this).find('.post-action').css('visibility', 'visible');
    });
    $(document).on('mouseleave', 'td[data-column-id=title]', function(){
        $(this).find('.post-action').css('visibility', 'hidden');
    });

    $(document).on('click', '#add-new-form', async function(e){
        e.preventDefault();
        const { value: title } = await Swal.fire({
            input: "text",
            inputLabel: formipay_forms_page.modal.add.title,
            showCancelButton: true,
            confirmButtonText: formipay_forms_page.modal.add.confirmButton,
            cancelButtonText: formipay_forms_page.modal.add.cancelButton,
            reverseButtons: true,
            inputValidator: (value) => {
                if (!value) {
                    return formipay_forms_page.modal.add.validation;
                }
            }
        }).then((result) => {
            /* Read more about isConfirmed, isDenied below, input value is ${coupon_code} */ 
            if (result.isConfirmed && result.value) {
                $.ajax({
                    type: 'post',
                    url: formipay_forms_page.ajax_url,
                    data: {
                        action: 'formipay-create-form-post',
                        title: result.value,
                        _wpnonce: formipay_forms_page.nonce
                    },
                    success: function (res) {
                        if(res.success){
                            window.location.href = res.data.edit_post_url;
                        }else{
                            Swal.fire({
                                html: res.data.message,
                                icon: 'error'
                            });
                        }
                    }
                });
            }
        });
    });

    $(document).on('click', '.delete-form', function(e){
        e.preventDefault();
        var data_id = $(this).attr('data-id');
        Swal.fire({
            icon: 'info',
            html: formipay_forms_page.bulk_delete.question,
            showCancelButton: true,
            confirmButtonText: formipay_forms_page.delete.confirmButton,
            cancelButtonText: formipay_forms_page.delete.cancelButton,
        }).then((result) => {
            /* Read more about isConfirmed, isDenied below */
            if (result.isConfirmed) {
                $.ajax({
                    type: 'post',
                    url: formipay_forms_page.ajax_url,
                    data: {
                        action: 'formipay-delete-form',
                        id: data_id,
                        _wpnonce: formipay_forms_page.nonce
                    },
                    success: function (res) {
                        Swal.fire({
                            title: res.data.title,
                            html: res.data.message,
                            icon: res.data.icon
                        });
                        formipay_table_grid.forceRender();
                    }
                });
            }
        });
    });

    $(document).on('click', '.duplicate-form', function(e){
        e.preventDefault();
        var data_id = $(this).attr('data-id');
        Swal.fire({
            icon: 'info',
            html: "Do you want to duplicate the form?",
            showCancelButton: true,
            confirmButtonText: "Confirm",
        }).then((result) => {
            /* Read more about isConfirmed, isDenied below */
            if (result.isConfirmed) {
                $.ajax({
                    type: 'post',
                    url: formipay_forms_page.ajax_url,
                    data: {
                        action: 'formipay-duplicate-form',
                        id: data_id,
                        _wpnonce: formipay_forms_page.nonce
                    },
                    success: function (res) {
                        Swal.fire({
                            title: res.data.title,
                            html: res.data.message,
                            icon: res.data.icon
                        });
                        formipay_table_grid.forceRender();
                    }
                });
            }
        });
    });

});