const categoryChoices = new Choices('#categories', {
    searchEnabled: true,
    searchChoices: false, // Prevent Choices.js from filtering the local list
    searchResultLimit: 10, // Optional: Limit visible results
    placeholder: true,
    placeholderValue: formipay_products_page.filter_form.categories.placeholder,
    noResultsText: formipay_products_page.filter_form.categories.noresult_text,
    itemSelectText: '',
    allowHTML: true
});

const currencyChoices = new Choices('#currencies', {
    searchEnabled: true,
    searchChoices: false, // Prevent Choices.js from filtering the local list
    searchResultLimit: 10, // Optional: Limit visible results
    placeholder: true,
    placeholderValue: formipay_products_page.filter_form.currencies.placeholder,
    noResultsText: formipay_products_page.filter_form.currencies.noresult_text,
    itemSelectText: '',
    allowHTML: true
});

const searchInput = document.querySelectorAll('.currency .choices__input--cloned');
let typingTimer;

searchInput[0].addEventListener('input', function () {
    const query = this.value;

    if (query.length >= 3) {
        clearTimeout(typingTimer);
        typingTimer = setTimeout(() => {
            fetchChoices(query);
        }, 300); // Add a debounce delay
    }
});

function fetchChoices(query) {
    fetch(formipay_products_page.ajax_url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
        },
        body: new URLSearchParams({
            action: 'formipay_product_get_currencies',
            search: query,
            _wpnonce: formipay_products_page.nonce
        }),
    })
    .then((response) => response.json())
    .then((data) => {
        currencyChoices.clearChoices();
        currencyChoices.setChoices( data, 'value', 'label', true);
    })
    .catch((error) => console.error('Error:', error));
}

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);
});

jQuery(function($){

    let formipay_product_table_grid = new gridjs.Grid({
        server: {
            url: formipay_products_page.ajax_url+'?action=formipay-tabledata-products&post_status='+document.getElementById('post_status').value+'&currency='+document.getElementById('currencies').value+'&category='+document.getElementById('categories').value+'&orderby='+document.getElementById('orderby').value+'&sort='+document.getElementById('sort_by').value+'&search='+document.getElementById('keyword').value+'&_wpnonce='+formipay_products_page.nonce,
            then: data => {
            
                if(data.posts_report){
                    processPostsReport(data.posts_report);
                }
    
                return data.results.map(
                    product => [product.ID, product.ID, product.title, product.price, product.type, product.stock, product.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_products_page.columns.id,
                width: '75px'
            },
            {
                name: formipay_products_page.columns.title,
                formatter: (_, row) => gridjs.html(`
                    <b>${_}</b><br>
                    <span class="post-action" style="visibility: hidden;">
                    <a href="${formipay_products_page.site_url}/wp-admin/post.php?post=${row.cells[0].data}&action=edit">edit</a> | <a href="#" class="delete-product" data-id="${row.cells[0].data}">delete</a> | <a href="#" class="duplicate-product" data-id="${row.cells[0].data}">duplicate</a>
                    </span>
                `)
            },
            {
                name: formipay_products_page.columns.price,
                formatter: (_, row) => gridjs.html(`
                    <span class="price">
                    <img src="${_.flag}" width="20"> ${_.name}
                    </span>
                `)
            },
            {
                name: formipay_products_page.columns.type
            },
            {
                name: formipay_products_page.columns.stock,
                formatter: (_, row) => gridjs.html(`
                    <span class="type-capsule the-type">${_}</span>
                `)
            },
            {
                name: formipay_products_page.columns.status, // { used: 1, limit: 5 }
                formatter: (_, row) => gridjs.html(`
                    <span class="status-label ${_}">${_}</span>
                `)
            },
        ],
        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-products'));

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

    function refresh_table_with_filter() {
        formipay_product_table_grid.updateConfig({
            server: {
                url: formipay_products_page.ajax_url+'?action=formipay-tabledata-products&post_status='+document.getElementById('post_status').value+'&currency='+document.getElementById('currencies').value+'&category='+document.getElementById('categories').value+'&orderby='+document.getElementById('orderby').value+'&sort='+document.getElementById('sort_by').value+'&search='+document.getElementById('keyword').value+'&_wpnonce='+formipay_products_page.nonce,
                then: data => data.results.map(
                    product => [product.ID, product.ID, product.title, product.price, product.type, product.stock, product.status]
                ),
                total: data => data.total
            }
        }).forceRender();
        $(document) = $('.formipay-grid-table');
    }

    $('.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-product', async function(e){
        e.preventDefault();

        var options = [];
        $.each(formipay_products_page.modal.form.currency_options, function(value, label){
            options.push(`<option value="${value}">${label}</option>`);
        });
    
        // Table-based form HTML
        const formHtml = `
            <input id="swal-input-title" class="swal2-input" placeholder="Product Title">
            <input id="swal-input-price" type="number" min="0" class="swal2-input" placeholder="Price">
        `;
    
        // Show the SweetAlert2 modal
        const { value: title } = await Swal.fire({
            input: "text",
            inputLabel: formipay_products_page.modal.add.title,
            showCancelButton: true,
            confirmButtonText: formipay_products_page.modal.add.confirmButton,
            cancelButtonText: formipay_products_page.modal.add.cancelButton,
            reverseButtons: true,
            inputValidator: (value) => {
                if (!value) {
                    return formipay_products_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_products_page.ajax_url,
                    data: {
                        action: 'formipay-create-product-post',
                        title: result.value,
                        _wpnonce: formipay_products_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-product', function(e){
        e.preventDefault();
        var data_id = $(this).attr('data-id');
        Swal.fire({
            icon: 'info',
            html: formipay_products_page.modal.delete.question,
            showCancelButton: true,
            confirmButtonText: formipay_products_page.modal.delete.confirmButton,
            cancelButtonText: formipay_products_page.modal.delete.cancelButton,
        }).then((result) => {
            /* Read more about isConfirmed, isDenied below */
            if (result.isConfirmed) {
                $.ajax({
                    type: 'post',
                    url: formipay_products_page.ajax_url,
                    data: {
                        action: 'formipay-delete-product',
                        id: data_id,
                        _wpnonce: formipay_products_page.nonce
                    },
                    success: function (res) {
                        Swal.fire({
                            title: res.data.title,
                            html: res.data.message,
                            icon: res.data.icon
                        });
                        updateDeleteButtonVisibility();
                        refresh_table_with_filter();
                    }
                });
            }
        });
    });

    $(document).on('click', '.duplicate-product', function(e){
        e.preventDefault();
        var data_id = $(this).attr('data-id');
        Swal.fire({
            icon: 'info',
            html: formipay_products_page.modal.duplicate.question,
            showCancelButton: true,
            confirmButtonText: formipay_products_page.modal.duplicate.confirmButton,
            cancelButtonText: formipay_products_page.modal.duplicate.cancelButton,
        }).then((result) => {
            /* Read more about isConfirmed, isDenied below */
            if (result.isConfirmed) {
                $.ajax({
                    type: 'post',
                    url: formipay_products_page.ajax_url,
                    data: {
                        action: 'formipay-duplicate-product',
                        id: data_id,
                        _wpnonce: formipay_products_page.nonce
                    },
                    success: function (res) {
                        Swal.fire({
                            title: res.data.title,
                            html: res.data.message,
                            icon: res.data.icon
                        });
                        updateDeleteButtonVisibility();
                        refresh_table_with_filter();
                    },
                    error: function(xhr, status, error) {
                        Swal.fire({
                            title: 'Error!',
                            html: xhr.responseText,
                            icon: 'error',
                            customClass: {
                                confirmButton: 'formipay-button-error'
                            },
                            allowOutsideClick: false,
                            allowEscapeKey: false,
                            showCloseButton: false,
                        }).then((result) => {
                            if (result.isConfirmed) {
                                window.location.reload();
                            }
                        });
                    }
                });
            }
        });
    });

});