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

define([
    'jquery',
    'ko',
    'underscore',
    'Magento_Ui/js/grid/massactions',
    'WriteTextAI_WriteTextAI/js/modal/confirm',
    'WriteTextAI_WriteTextAI/js/model/grid/notifications',
    'WriteTextAI_WriteTextAI/js/model/edit/generate/currently-generating',
    'WriteTextAI_WriteTextAI/js/model/grid/error-messages',
    'WriteTextAI_WriteTextAI/js/model/grid/listing',
    'WriteTextAI_WriteTextAI/js/model/total-credits',
    'WriteTextAI_WriteTextAI/js/model/pro-badge',
    'WriteTextAI_WriteTextAI/js/model/grid/field-templates',
    'WriteTextAI_WriteTextAI/js/model/gallery',
    'WriteTextAI_WriteTextAI/js/model/edit/product',
    'mage/translate',
    'WriteTextAI_WriteTextAI/js/grid/reload',
    'WriteTextAI_WriteTextAI/js/utils/grid/actions',
    'WriteTextAI_WriteTextAI/js/model/grid/invalid-image-popup',
    'WriteTextAI_WriteTextAI/js/utils/grid/transfer',
    'WriteTextAI_WriteTextAI/js/utils/grid/generate',
    'WriteTextAI_WriteTextAI/js/utils/grid/keyword-analysis',
    'WriteTextAI_WriteTextAI/js/utils/grid/full-automation',
    'text!WriteTextAI_WriteTextAI/template/modal/bulk-generate.html',
    'text!WriteTextAI_WriteTextAI/template/modal/bulk-keyword-analysis.html',
    'text!WriteTextAI_WriteTextAI/template/modal/bulk-full-automation.html',
    'WriteTextAI_WriteTextAI/js/utils/signalr',
    'text!ui/template/modal/modal-popup.html',
    'Magento_Ui/js/modal/alert',
    'uiRegistry',
    'WriteTextAI_WriteTextAI/js/model/grid/ai-models',
    'WriteTextAI_WriteTextAI/js/model/signalr',
    'WriteTextAI_WriteTextAI/js/model/grid/bulk-actions',
    'WriteTextAI_WriteTextAI/js/model/grid/reference-products',
    'WriteTextAI_WriteTextAI/js/model/grid/selection',
    'mage/validation'
], function (
    $,
    ko,
    _,
    Massactions,
    confirm,
    notifications,
    currentlyGeneratingModel,
    errorMessagesModel,
    listingModel,
    totalCredits,
    proBadge,
    fieldTemplatesModel,
    galleryModel,
    product,
    $t,
    reloadGrid,
    gridUtils,
    gridInvalidImagePopupModel,
    transferUtils,
    generateUtils,
    keywordAnalysisUtils,
    fullAutomationUtils,
    bulkGeneratePopupTmpl,
    bulkKeywordAnalysisPopupTmpl,
    fullAutomationPopupTmpl,
    signalrUtils,
    modalPopupTmpl,
    alert,
    uiRegistry,
    aiModels,
    signalrModel,
    bulkActionsData,
    referenceProducts,
    selectionModel
) {
    'use strict';

    /**
     * @var {Component} self
     */
    var self;

    return Massactions.extend({
        defaults: {
            template: 'WriteTextAI_WriteTextAI/grid/actions',
            gridName: 'wtai_products_grid_listing.wtai_products_grid_listing_data_source',
            generateFormSelector: '#wtaiBulkGenerateForm',
            transferFormSelector: '#wtaiBulkTransferForm',
            keywordAnalysisFormSelector: '#wtaiBulkKeywordAnalysisForm',
            fullAutomationFormSelector: '#wtaiFullAutomationForm',
            statusRunning: 'Running',
            defaultStoreId: 0,
            currentUser: {},
            initTransfer: false,
            isTransferOngoing: false
        },

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

            self = this;

            this.currentUser.subscribe(function (currentUser) {
                if (currentUser && Object.keys(currentUser).length !== 0) {
                    listingModel.currentUser(currentUser);
                    gridInvalidImagePopupModel.currentUser(currentUser);
                    transferUtils.continueBulkTransfer(this);
                }
            }, this);

            this.ids.subscribe(function (ids) {
                listingModel.ids(ids);
            }, this);

            signalrModel.triggerContinueBulkTransfer.subscribe(function (triggerContinueBulkTransfer) {
                if (triggerContinueBulkTransfer && this.initTransfer) {
                    transferUtils.continueBulkTransfer(this);
                }
                this.initTransfer = true;
            }, this);
        },

        /** @inheritdoc */
        initObservable: function () {
            this._super()
                .observe([
                    'currentUser',
                    'ids',
                    'isTransferOngoing'
                ]);

            this.isDisabled = ko.computed(function () {
                var bulkGenerateOngoing = notifications.statuses().some((status) => {
                    var statuses = ['Cancelled', 'Completed', 'Failed'];
                    if ((status.recordType || 'Product') !== 'Product') {
                        return false;
                    }
                    if (signalrUtils.isCancelling(status) && status.user === this.currentUser().email) {
                        return true;
                    }
                    return (
                        !statuses.includes(status.status) &&
                        status.user === this.currentUser().email
                    );
                }, this);
                var disableBulkSelect = bulkActionsData.getDisableBulkSelect('Product')();

                return bulkGenerateOngoing || disableBulkSelect;
            }, this);

            this.isLoading = ko.computed(function () {
                return bulkActionsData.getIsLoading('Product')();
            }, this);

            return this;
        },

        /**
         * Disable action if user does not have pro access
         *
         * @param {string} actionType - Action type.
         *
         * @returns {boolean}
         */
        disableAction: function (actionType) {
            var proActions = ['keyword_analysis', 'full_automation'];
            return !totalCredits.hasProAccess() && proActions.includes(actionType);
        },

        /**
         * Show badge if user does not have pro access
         *
         * @param {Object} action - Action data.
         *
         * @returns {boolean}
         */
        showBadge: function (action) {
            return proBadge.showBadge() && action.pro === true;
        },

        /** @inheritdoc */
        applyAction: function (actionIndex) {
            var data = this.getSelections(),
                action,
                callback,
                disabledRowIds = [];
            const maxItems = 5000;
            const minItems = 2;
            
            if (this.isDisabled() || this.disableAction(actionIndex)) {
                return;
            }

            _.each(data.selected, function (entity_id) {
                if (this.isRowDisabled(entity_id)) {
                    data.selected = _.without(data.selected, entity_id);
                    data.total--;
                    disabledRowIds.push(entity_id);
                }
            }, this);
            bulkActionsData.getDisabledRowIds('Product')(disabledRowIds);

            if (selectionModel && selectionModel.selectedIds) {
                selectionModel.selectedIds(data.selected || []);
            }

            if (data.total && data.total < minItems) {
                alert({
                    content: $t('Select at least two items to perform a bulk action.')
                });

                return this;
            }

            if (data.total && data.total > maxItems) {
                alert({
                    content: $t('The maximum limit for bulk processing is %s products.').replace('%s', maxItems)
                });

                return this;
            }

            if (!data.total) {
                alert({
                    content: this.noItemsMsg
                });

                return this;
            }

            action   = this.getAction(actionIndex);
            callback = this._getCallback(action, data);

            action.confirm ?
                this._confirm(action, callback) :
                callback();

            return this;
        },

        /**
         * Default action callback. Sends selections data
         * via POST request.
         *
         * @param {Object} action - Action data.
         * @param {Object} data - Selections data.
         *
         * @returns {void}
         */
        defaultCallback: function (action, _data) {
            var settings = {};
            var data = JSON.parse(JSON.stringify(_data));

            errorMessagesModel.messages([]);

            try {
                window.localStorage.setItem(
                    bulkActionsData.getDeselectStorageKey('Product'),
                    String(Date.now())
                );
            } catch (e) {
                // no-op
            }

            try {
                switch (action.type) {
                    case 'generate':
                        settings = gridUtils.convertForm($(this.generateFormSelector));
                        generateUtils.bulkGenerate(this, action, data, settings);
                        break;
                    case 'transfer':
                        settings = gridUtils.convertForm($(this.transferFormSelector));
                        transferUtils.transferable(this, action, data, settings);
                        break;
                    case 'keyword_analysis':
                        settings = gridUtils.convertForm($(this.keywordAnalysisFormSelector));
                        keywordAnalysisUtils.bulkKeywordAnalysis(this, action, data, settings);
                        break;
                    case 'full_automation':
                        settings = gridUtils.convertForm($(this.fullAutomationFormSelector));
                        fullAutomationUtils.fullAutomation(this, action, data, settings);
                        break;
                    default:
                        this._super(action, data);
                }
            } catch (e) {
                errorMessagesModel.messages.push(window.wtaGeneralErrorMessage);
            }
        },

        /**
         * Bulk full automation
         *
         * @param {Object} _self - Self data.
         * @param {Object} action - Action data.
         * @param {Object} data - Selections data.
         * @param {Object} settings - Form settings.
         */
        fullAutomationRequest: function (_self, action, data, settings) {
            fullAutomationUtils.bulkGenerateRequest(_self, action, data, settings);
        },

        /**
         * Bulk generate
         *
         * @param {Object} _self - Self data.
         * @param {Object} action - Action data.
         * @param {Object} data - Selections data.
         * @param {Object} settings - Form settings.
         *
         * @returns {void}
         */
        bulkGenerateRequest: function (_self, action, data, settings) {
            generateUtils.bulkGenerateRequest(_self, action, data, settings);
        },

        /**
         * Bulk keyword analysis
         *
         * @param {Object} _self - Self data.
         * @param {Object} action - Action data.
         * @param {Object} data - Selections data.
         * @param {Object} settings - Form settings.
         *
         * @returns {void}
         */
        bulkKeywordAnalysisRequest: function (_self, action, data, settings) {
            keywordAnalysisUtils.bulkKeywordAnalysisRequest(_self, action, data, settings);
        },

        /**
         * Reload grid.
         */
        gridReload: function () {
            var showLoader = false;
            var debounce = true;

            reloadGrid.reloadUIComponent(
                'wtai_products_grid_listing.wtai_products_grid_listing_data_source',
                showLoader,
                debounce
            );
        },

        /**
         * Check template selection for required fields
         *
         * @param {string} actionType - Type of action (generate, full_automation)
         *
         * @returns {boolean} - Returns true if templates are selected for all required fields
         */
        checkTemplateSelection: function (actionType) {
            /**
             * Define the field types that require template validation
             */
            var requiredTemplateFields = ['page_title', 'product_description', 'short_product_description'];
            
            var fieldEquivalent = {
                'page_title': 'page title',
                'page_description': 'page description',
                'product_description': 'product description',
                'short_product_description': 'excerpt'
            };
            /**
             * Get selected fields
             */
            var selectedFields = [];
            var formSelector = actionType === 'generate' ? '#wtaiBulkGenerateForm' : '#wtaiFullAutomationForm';
            var fieldsCheckboxes = $(formSelector + ' input[name="fields[]"]:checked');
            fieldsCheckboxes.each(function () {
                selectedFields.push($(this).val());
            });
            
            /**
             * Check if any of the required fields are selected
             */
            var hasRequiredField = selectedFields.some(function (field) {
                return requiredTemplateFields.includes(field);
            });
            
            /**
             * If no required fields are selected, don't show template confirmation
             */
            if (!hasRequiredField) {
                return true; /** Return true to skip template validation */
            }
            
            /**
             * Check for template selection for the required fields
             */
            var hasTemplateForRequiredFields = false;
            var hasTemplateForAllFields = true;

            console.log(fieldTemplatesModel.templateSettings());
            
            if (fieldTemplatesModel.templateSettings().length === 0) {
                /** skip template validation if no templates are available */
                return true;
            }

            var isThereAvailableTemplateForSelectedFields = false;
            selectedFields.forEach(function (fieldType) {
                if (fieldTemplatesModel.templateSettings()[fieldEquivalent[fieldType]]) {
                    isThereAvailableTemplateForSelectedFields = true;
                }
            })

            if (!isThereAvailableTemplateForSelectedFields) {
                /** skip template validation if no templates are available for selected fields */
                return true;
            }
            
            requiredTemplateFields.forEach(function (fieldType) {
                /**
                 * fieldTemplatesModel.templateSettings()[fieldEquivalent[fieldType]] is for
                 * checking if field has available templates.
                 *
                 * Remove the condition if template selection is not a factor
                 * in showing empty template confirmation.
                 */
                if (selectedFields.includes(fieldType)
                    && fieldTemplatesModel.templateSettings()[fieldEquivalent[fieldType]]
                ) {
                    /**
                     * Use hasTemplateForRequiredFields in return if we
                     * only want to check at least one template is selected.
                     */
                    if (actionType === 'generate') {
                        /** Check if template is selected for this field type */
                        var templateSelect = $('select[name="wtai_generate_template_' + fieldType.replace(' ', '_') + '"]');
                        if (templateSelect.length && templateSelect.val()) {
                            hasTemplateForRequiredFields = true;
                        } else {
                            hasTemplateForAllFields = false;
                        }
                    } else {
                        /** Check if template is selected for this field type */
                        var templateSelect = $('select[name="wtai_template_' + fieldType.replace(' ', '_') + '"]');
                        if (templateSelect.length && templateSelect.val()) {
                            hasTemplateForRequiredFields = true;
                        } else {
                            hasTemplateForAllFields = false;
                        }
                    }
                }
            });

            return hasTemplateForRequiredFields;
        },

        /**
         * Show empty template confirmation dialog
         *
         * @param {Function} callback - Callback function to execute after confirmation
         *
         * @returns {void}
         */
        showEmptyTemplateConfirmation: function (callback) {
            $('.wtai-empty-template-confirm').show();

            /**
             * Bind continue button
             */
            $('.wtai-empty-template-confirm .action-accept').off('click.emptyTemplate').on('click.emptyTemplate', function (e) {
                e.preventDefault();
                e.stopPropagation();
                $('.wtai-empty-template-confirm').hide();
                if (typeof callback === 'function') {
                    callback();
                }
            });
            
            /**
             * Bind go back button
             */
            $('.wtai-empty-template-confirm .action-back').off('click.emptyTemplate').on('click.emptyTemplate', function (e) {
                e.preventDefault();
                e.stopPropagation();
            
                /**
                 * Switch to templates tab when popup is shown
                 */
                var templatesTab = $('.wtai-bulk-generate-popup .item.title a[href="#wtai-templates"], .wtai-bulk-full-automation-popup .item.title a[href="#wtai-templates"]');
                if (templatesTab.length && !templatesTab.hasClass('switch')) {
                    templatesTab.trigger('click');
                }
                
                /**
                 * Alternative approach - look for tab by text content
                 */
                if (templatesTab.length === 0) {
                    $('.wtai-bulk-generate-popup .item.title a, .wtai-bulk-full-automation-popup .item.title a').each(function () {
                        if ($(this).text().toLowerCase().includes('template')) {
                            $(this).trigger('click');
                            return false;
                        }
                    });
                }
                
                $('.wtai-empty-template-confirm').hide();
            });
            
            /**
             * Bind overlay click to close (same as go back)
             */
            $('.wtai-empty-template-confirm .wtai-empty-template-confirm-overlay').off('click.emptyTemplate').on('click.emptyTemplate', function (e) {
                e.preventDefault();
                e.stopPropagation();
                $('.wtai-empty-template-confirm').hide();
            });
        },

        /**
         * Validate AI model selection
         *
         * @param {string} actionType - Type of action (generate, full_automation)
         *
         * @returns {boolean} - Returns true if AI model is selected
         */
        validateAiModelSelection: function (actionType) {
            switch (actionType) {
                case 'generate':
                    /* if (aiModels.BulkGeneratehasAiModelsAndNotSelected()) {
                        return window.confirm($t('An AI model is available. Do you want to proceed without using it?'));
                    } */
                    return true;
                case 'full_automation':
                    /* if (aiModels.FullAutohasAiModelsAndNotSelected()) {
                        return window.confirm($t('An AI model is available. Do you want to proceed without using it?'));
                    } */
                    return true;
                default:
                    return true;
            }
        },

        /**
         * Shows actions' confirmation window.
         *
         * @param {Object} action - Actions' data.
         * @param {Function} callback - Callback that will be
         *      invoked if action is confirmed.
         *
         * @returns {void}
         */
        _confirm: function (action, callback) {
            const actionType = action.type;
            const confirmData = action.confirm;

            if (!['generate', 'transfer', 'keyword_analysis', 'full_automation'].includes(actionType)) {
                return this._super(action, callback);
            }

            const actionConfig = {
                generate: {
                    buttonText: confirmData.button,
                    modalClass: 'wtai-modal wtai-bulk-generate-popup wtai-confirm',
                    formSelector: this.generateFormSelector,
                    popupTpl: bulkGeneratePopupTmpl
                },
                transfer: {
                    buttonText: $t('Transfer'),
                    modalClass: 'wtai-modal wtai-bulk-transfer-popup wtai-transfer',
                    formSelector: this.transferFormSelector,
                    popupTpl: modalPopupTmpl
                },
                keyword_analysis: {
                    buttonText: $t('Start AI-powered keyword analysis'),
                    modalClass: 'wtai-modal wtai-bulk-keyword-analysis-popup',
                    formSelector: this.keywordAnalysisFormSelector,
                    popupTpl: bulkKeywordAnalysisPopupTmpl
                },
                full_automation: {
                    buttonText: $t('Run full automation'),
                    modalClass: 'wtai-modal wtai-bulk-full-automation-popup wtai-confirm',
                    formSelector: this.fullAutomationFormSelector,
                    popupTpl: fullAutomationPopupTmpl
                }
            };

            const config = actionConfig[actionType];

            confirm({
                creditCostText: $t('How is credit cost calculated?'),
                title: confirmData.title,
                content: confirmData.message,
                modalClass: config.modalClass,
                popupTpl: config.popupTpl,
                actions: {
                    confirm: callback,
                    cancel: () => {
                        $('body').removeClass('_has-modal');
                        reloadGrid.reloadUIComponent(self.gridName, false, true);
                    }
                },
                buttons: [{
                    text: $t('Cancel'),
                    class: 'action-secondary action-dismiss',
                    click: function (event) {
                        this.closeModal(event);
                    }
                }, {
                    text: config.buttonText,
                    class: 'action-primary action-accept',
                    click: function (event) {
                        event.preventDefault();
                        event.stopPropagation();
                        
                        const confirmSelf = this;
                        const $form = $(config.formSelector);
                        
                        const isFormValid = function () {
                            return !!(
                                $form.data('validator') &&
                                $form.validation() &&
                                $form.validation('isValid')
                            );
                        };

                        const proceedWithSubmission = function () {
                            confirmSelf.closeModal(event, true);
                            $('body').removeClass('_has-modal');
                        };
                        
                        const handleTemplateValidation = function () {
                            /** Check if this is a bulk generate or full automation action */
                            if (actionType === 'generate' || actionType === 'full_automation') {
                                /** Get the empty template confirm component */
                                const emptyTemplateConfirm = uiRegistry.get('wtaiEmptyTemplateConfirm');
                                
                                if (emptyTemplateConfirm) {
                                    console.log('emptyTemplateConfirm', emptyTemplateConfirm);
                                    /** This will either proceed directly or show the confirmation popup */
                                    emptyTemplateConfirm.validateTemplateSelection(proceedWithSubmission);
                                } else {
                                    console.log('emptyTemplateConfirm not found');
                                    /** Fallback: Check template selection manually using the extracted method */
                                    const hasTemplate = self.checkTemplateSelection(actionType);
                                    
                                    if (!hasTemplate) {
                                        /** Show confirmation popup manually using the extracted method */
                                        self.showEmptyTemplateConfirmation(proceedWithSubmission);
                                    } else {
                                        /** Proceed normally */
                                        proceedWithSubmission();
                                    }
                                }
                            } else {
                                /** For other actions (transfer, keyword_analysis), proceed normally */
                                proceedWithSubmission();
                            }
                        };
                        
                        /* if (self.validateAiModelSelection(actionType)) {
                            handleTemplateValidation();
                        } */

                        if (!isFormValid()) {
                            return;
                        }

                        handleTemplateValidation();
                    }
                }]
            });
        },
        /**
         * Check if row is disabled.
         *
         * @param {Object} row
         * @returns {Boolean}
         */
        isRowDisabled: function (entity_id) {
            try {
                var isSingleGenerating = signalrModel.generating() && product.productId() === entity_id,
                    productsUploading = galleryModel.productsUploading().includes(entity_id),
                    isBulkGenerating = notifications.statuses().some((status) => {
                        if ((status.recordType || 'Product') !== 'Product') {
                            return false;
                        }
                        var isQueued =
                            (status.status === this.statusRunning || status.status === 'Pending') && (
                                status.queuedIds.indexOf(entity_id) !== -1 ||
                                status.runningIds.indexOf(entity_id) !== -1 ||
                                status.completedIds.indexOf(entity_id) !== -1
                            );
                        
                        return isQueued;
                    }, this),
                    isBulkCancelling = notifications.statuses().some((status) => {
                        if ((status.recordType || 'Product') !== 'Product') {
                            return false;
                        }
                        return (status.status === 'Cancelling' && (
                                status.queuedIds.indexOf(entity_id) !== -1 ||
                                status.runningIds.indexOf(entity_id) !== -1 ||
                                status.completedIds.indexOf(entity_id) !== -1
                            ));
                    }, this);
                var isOtherUserSingleGenerating = signalrModel.singleGeneratingStatuses().some(function (status) {
                    return status.recordId == entity_id &&
                            status.storeId == referenceProducts.storeId() &&
                            status.generationType == 'Product' &&
                            !status.stop;
                });
                var currentlyGeneratingRecordIdentifiers = currentlyGeneratingModel.recordIdentifiers();
                var productIdentifier = 'Product' + '_' + entity_id + '_' + referenceProducts.storeId();
                var isCurrentlyGenerating = currentlyGeneratingRecordIdentifiers.includes(productIdentifier);
                var isDisabled = isBulkGenerating
                    || isSingleGenerating || productsUploading || isOtherUserSingleGenerating
                    || isBulkCancelling || isCurrentlyGenerating;

                return isDisabled;
            } catch (error) {
                console.log(error);
                return false;
            }
        },
    });
});
