/**
 * @author 1902 Software
 * @copyright Copyright © 2023 1902 Software (https://1902software.com/magento/)
 * @package WriteTextAI_WriteTextAI
 */

define([
    'Magento_Ui/js/grid/provider',
    'WriteTextAI_WriteTextAI/js/utils/grid/filters',
    'WriteTextAI_WriteTextAI/js/categories/model/edit',
    'WriteTextAI_WriteTextAI/js/model/edit',
    'WriteTextAI_WriteTextAI/js/model/grid/bulk-actions'
], function (
    Provider,
    filtersUtils,
    categoryEditData,
    productEditData,
    bulkActionsData
) {
    'use strict';

    return Provider.extend({
        defaults: {
            isLoading: false,
            currentRequest: null,
            pendingRequests: [],
            isEditPageOpen: false,
            hasPendingReload: false,
            pendingReloadOptions: null
        },


        /**
         * @inheritdoc
         */
        initialize: function () {
            this._super();

            categoryEditData.opened.subscribe(function (opened) {
                this.isEditPageOpen = opened;
                if (opened) {
                    /** Abort all pending requests when category edit page opens */
                    this.abortAllPendingRequests();
                }
            }, this);

            productEditData.opened.subscribe(function (opened) {
                this.isEditPageOpen = opened;
                if (opened) {
                    /** Abort all pending requests when product edit page opens */
                    this.abortAllPendingRequests();
                }
            }, this);

            /** Listen for tab visibility changes */
            this.initTabVisibilityListener();
        },

        /**
         * @inheritdoc
         */
        reload: function (options) {
            var custom,
                showLoader,
                debounce,
                request;

            options = options || {};

            custom =
                typeof options.custom !== 'undefined'
                    ? options.custom
                    : false;
            showLoader =
                typeof options.showLoader !== 'undefined'
                    ? options.showLoader
                    : true;
            debounce =
                typeof options.debounce !== 'undefined'
                    ? options.debounce
                    : false;

            /** Prevent reload when edit page is open */
            if (custom && this.isEditPageOpen) {
                return;
            }

            /** Prevent reload when tab is not visible, but store options for single reload later */
            if (custom && document.hidden) {
                this.hasPendingReload = true;
                this.pendingReloadOptions = options;
                return;
            }

            /** Prevent reload if debounce is enabled and grid is already loading */
            if (custom && debounce && this.isLoading) {
                return;
            }

            /** Allow parallel requests - do not abort previous request */
            /**
             * if (this.currentRequest) {
             *    this.currentRequest.abort();
             * }
             */

            this.isLoading = true;
            var recordType = this.params && this.params.namespace === 'wtai_categories_grid_listing' ? 'Category' : 'Product';
            bulkActionsData.getDisableBulkSelect(recordType)(true);
            bulkActionsData.getIsLoading(recordType)(true);
            /** showLoader = true; */

            if (this.params.filters) {
                filtersUtils.resetTargetObject(this.params.filters, this);
                filtersUtils.addDefaultWtaiFilters(this.params.filters, this, this.params.namespace === 'wtai_categories_grid_listing');
                
                if (this.params.filters['writetextai_status']) {
                    filtersUtils.processCustomUrlFilters(this.params.filters['writetextai_status'], this);
                }
                
                filtersUtils.processRecordIdsFilter(this.params.filters, this);
                filtersUtils.processRequestIdFilter(this.params.filters, this);
            }
            console.log('this.params', this.params);
            request = this.storage().getData(this.params, options);
            this.currentRequest = request;
            /** Track this request in pending requests array */
            this.pendingRequests.push(request);

            if (custom) {
                if (showLoader) {
                    this.trigger('reload');
                }
            } else {
                this.trigger('reload');
            }

            /** Capture request in closure to ensure correct removal from pending array */
            request.done(function (data) {
                this.onReload(data, request);
            }.bind(this)).fail(function (xhr) {
                this.onError(xhr, request);
            }.bind(this));

            return request;
        },

        /**
         * @inheritdoc
         * @param {Object} data
         * @param {Object} completedRequest - The specific request that completed
         */
        onReload: function (data, completedRequest) {
            this._super(data);

            this.isLoading = false;
            /** Remove completed request from pending requests */
            var index = this.pendingRequests.indexOf(completedRequest);
            if (index > -1) {
                this.pendingRequests.splice(index, 1);
            }
            /** Clear currentRequest if it's the one that completed */
            if (this.currentRequest === completedRequest) {
                this.currentRequest = null;
            }
            /** Clear pending reload flag and options after successful reload */
            this.hasPendingReload = false;
            this.pendingReloadOptions = null;
            if (this.pendingRequests.length === 0) {
                var recordType = this.params && this.params.namespace === 'wtai_categories_grid_listing' ? 'Category' : 'Product';
                bulkActionsData.getDisableBulkSelect(recordType)(false);
                bulkActionsData.getIsLoading(recordType)(false);
            }
        },

        /**
         * @inheritdoc
         * @param {Object} xhr
         * @param {Object} failedRequest - The specific request that failed
         */
        onError: function (xhr, failedRequest) {
            this.isLoading = false;
            /** Remove failed request from pending requests */
            var index = this.pendingRequests.indexOf(failedRequest);
            if (index > -1) {
                this.pendingRequests.splice(index, 1);
            }
            /** Clear currentRequest if it's the one that failed */
            if (this.currentRequest === failedRequest) {
                this.currentRequest = null;
            }
            /** Re-enable bulk actions if no pending requests remain */
            if (this.pendingRequests.length === 0) {
                var recordType = this.params && this.params.namespace === 'wtai_categories_grid_listing' ? 'Category' : 'Product';
                bulkActionsData.getDisableBulkSelect(recordType)(false);
                bulkActionsData.getIsLoading(recordType)(false);
            }
            
            /** Call parent onError */
            this._super(xhr);
        },

        /**
         * Abort all pending requests
         */
        abortAllPendingRequests: function () {
            var i;
            /** Abort all pending requests */
            for (i = 0; i < this.pendingRequests.length; i++) {
                if (this.pendingRequests[i] && this.pendingRequests[i].abort) {
                    this.pendingRequests[i].abort();
                }
            }
            /** Clear the pending requests array */
            this.pendingRequests = [];
            this.currentRequest = null;
            this.isLoading = false;
        },

        /**
         * Initialize tab visibility listener
         */
        initTabVisibilityListener: function () {
            var self = this;
            
            document.addEventListener('visibilitychange', function () {
                /** Execute single reload when tab becomes visible if any were pending */
                if (!document.hidden && self.hasPendingReload) {
                    self.hasPendingReload = false;
                    var options = self.pendingReloadOptions;
                    self.pendingReloadOptions = null;
                    /** Execute single reload with stored options */
                    self.reload(options);
                }
            });
        },

        /**
         * Get parameter by name
         *
         * @param {String} name
         *
         * @returns {String}
         */
        getParameterValueByName: function (name) {
            var url = new URL(window.location.href),
                searchParams = new URLSearchParams(url.search),
                value = searchParams.get(name);

            return value ? value : '';
        }
    });
});
