jQuery(function ($) {
    var isApplyingPredefinedRange = false;

    function updateDateInput($input, tsMs) {
        window.anbarakSetDatePickerValue($input, tsMs);
    }

    function formatDateDisplay(val) {
        if (!val) return '';
        var parts = val.split(',');
        return parts.length > 1 ? parts[1].trim().replace(/,.*$/, '') : val;
    }

    function updateDateRangeDisplay($form) {
        var rangeEl = $form.closest('.filter-form-wrapper').find('#report-date-range');
        if (!rangeEl.length) return;
        rangeEl.find('.date-range-from').text(formatDateDisplay($form.find('input[name="date-from"]').val()));
        rangeEl.find('.date-range-to').text(formatDateDisplay($form.find('input[name="date-to"]').val()));
    }

    function applyPredefinedRange($button) {
        const $form = $button.closest('form');

        if (!$form.length) return;

        var fromTs = parseInt($button.data('date-from'));
        var toTs = parseInt($button.data('date-to'));

        if (isNaN(fromTs) || isNaN(toTs)) return;

        isApplyingPredefinedRange = true;
        updateDateInput($form.find('input[name="date-from"]'), fromTs * 1000);
        updateDateInput($form.find('input[name="date-to"]'), toTs * 1000);
        isApplyingPredefinedRange = false;
        updateDateRangeDisplay($form);
    }

    function initializeActivePredefinedRanges() {
        $('.filter-form-wrapper form').each(function () {
            var $form = $(this);
            var $activeButton = $form.find('.predefined-time-ranges-buttons .predefined-date-button.active').first();

            if ($activeButton.length) {
                applyPredefinedRange($activeButton);
            } else {
                updateDateRangeDisplay($form);
            }
        });
    }

    function fetchFilteredData(formId, holderId) {
        const $form = $(`#${formId}`);
        const $holder = $(`#${holderId}`);

        if ($holder.is('table') || $holder.is('tbody')) {
            const colspan = $holder.closest('table').find('thead th').length;
            $(`#${holderId}`).html(`
            <tr>
                <td colspan="${colspan}">
                     <div class="text-lg font-semibold text-gray-400 text-center p-5">
                         ${anbarak.i18n.loading}
                     </div>
                </td>
            </tr>`);
        } else {
            $(`#${holderId}`).block();
        }

        $.ajax({
            method: 'get',
            url: anbarak.ajax_url,
            data: $form.serialize()
        }).done(function (html) {
            if ('0' == html.trim()) {
                if ($holder.is('table') || $holder.is('tbody')) {
                    const colspan = $holder.closest('table').find('thead th').length;
                    $(`#${holderId}`).html(`
                        <tr>
                            <td colspan="${colspan}">
                                 <div class="text-lg font-semibold text-gray-400 text-center p-5">
                                     ${anbarak.i18n.nothing_found}
                                 </div>
                             </td>
                         </tr>`);
                } else {
                    $(`#${holderId}`).html(`
                        ${anbarak.i18n.nothing_found}
                     `);
                }
            } else {
                $(`#${holderId}`).html(html);
            }

            updateDateRangeDisplay($form);

            if ('function' === typeof window.renderExpensesStatsChart) {
                window.renderExpensesStatsChart()
            }

            if ('function' === typeof window.renderReportCharts) {
                window.renderReportCharts()
            }

        }).fail(function (response) {
            console.log('Error:', response);
        });
    }

    $(document).on('click', '.predefined-time-ranges-buttons .predefined-date-button', function (e) {
        const $button = $(this);

        $('.predefined-date-button').removeClass('active');
        $button.addClass('active');

        applyPredefinedRange($button);
    });

    $(document).on('click', '.filter-form-wrapper .product-type-buttons button', function (e) {
        const $button = $(this);
        const $form = $button.closest('form');

        $button.siblings().removeClass('active');
        $button.addClass('active');

        $form.find('.product_level').val($button.val());
    });

    function onIntersection(entries, opts) {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                const $holder = $(entry.target);
                const formId = $holder.data('filter-form') || $holder.attr('id').replace('-holder', '');
                const $form = $(`#${formId}`);

                if ($form.length) {
                    fetchFilteredData(formId, $holder.attr('id'));
                    observer.unobserve(entry.target);
                }
            }
        });
    }

    const observer = new IntersectionObserver(onIntersection, {
        root: null,
        threshold: 0
    });

    initializeActivePredefinedRanges();

    $('[id$="-holder"][data-filter-form], [id$="-holder"]').each(function () {
        observer.observe(this);
    });

    $(document).on('submit', '.filter-form-wrapper form', function (e) {
        e.preventDefault();

        const formId = $(this).attr('id');
        const holderId = formId.replace('frm-', '') + '-holder';

        fetchFilteredData(formId, holderId);
    });

    $(document).on('anbarak:date-picked', '.filter-form-wrapper input.date-picker, .filter-form-wrapper input.datetime-picker', function () {
        if (isApplyingPredefinedRange) return;

        $('.predefined-date-button').removeClass('active');
        updateDateRangeDisplay($(this).closest('.filter-form-wrapper').find('form'));
    });

});
