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

define([
    "jquery",
    "ko",
    "mage/translate",
    "uiComponent",
    "underscore",
    'WriteTextAI_WriteTextAI/js/model/grid/invalid-image-popup',
    'WriteTextAI_WriteTextAI/js/model/grid/upload-images',
    'WriteTextAI_WriteTextAI/js/model/grid/error-messages',
    'WriteTextAI_WriteTextAI/js/model/grid/notifications',
    'WriteTextAI_WriteTextAI/js/magento/grid/massactions',
    "Magento_Ui/js/modal/modal"
], function (
    $,
    ko,
    $t,
    Component,
    _,
    invalidImagePopupModel,
    uploadImages,
    errorMessagesModel,
    notifications,
    massactions
) {
    'use strict';

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

    return Component.extend({
        defaults: {
            defaultStoreId: 0,
            data: {},
            settings: {}
        },

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

            self = this;

            this.initModal();

            invalidImagePopupModel.data.subscribe(function (value) {
                this.data(value);
            }, this);

            invalidImagePopupModel.settings.subscribe(function (value) {
                this.settings(value);
            }, this);
        },

        /** @inheritdoc */
        initObservable: function () {
            this._super()
                .observe([
                    'data',
                    'settings'
                ]);
            
            this.proceedable = ko.computed(function () {
                var successImages = uploadImages.successImages(),
                    settings = this.settings(),
                    textTypes = [
                        'page_title',
                        'page_description',
                        'product_description',
                        'short_product_description',
                        'open_graph'
                    ];

                if (settings.fields && textTypes.some(textType => settings.fields.includes(textType))) {
                    return true;
                } else {
                    return successImages.length > 0;
                }
            }, this);

            this.isFullAutomationRequest = ko.computed(function () {
                return invalidImagePopupModel.isFullAutomationRequest();
            });

            this.failedImages = ko.computed(function () {
                return uploadImages.failedImages();
            });

            this.invalid = ko.computed(function () {
                return uploadImages.invalid().slice(0, 10);
            });

            this.notSupported = ko.computed(function () {
                return uploadImages.notSupported().slice(0, 10);
            });

            this.downloadFailed = ko.computed(function () {
                return uploadImages.downloadFailed().slice(0, 10);
            });

            this.general = ko.computed(function () {
                return uploadImages.general().slice(0, 10);
            });

            this.errorMessages = ko.computed(function () {
                return uploadImages.errorMessages();
            });

            return this;
        },

        /**
         * Initialize modal
         */
        initModal: function () {
            $('.wtai-grid-invalid-image-popup').modal({
                type: 'popup',
                responsive: true,
                title: $t('Some images could not be processed:'),
                modalClass: 'wtai-grid-invalid-image-popup-modal',
                overlayClass: 'modals-overlay wtai-grid-invalid-image-popup-overlay',
                buttons: [{
                    text: $t('Cancel'),
                    class: 'action-secondary action-dismiss',
                    click: function () {
                        this.closeModal();
                    }
                }, {
                    text: $t('Proceed'),
                    class: 'action-primary wtai-action-proceed',
                    click: function () {
                        self._generate(self.data(), self.settings());
                        this.closeModal();
                    }
                }, {
                    text: $t('Okay'),
                    class: 'action-primary wtai-action-okay',
                    click: function () {
                        this.closeModal();
                    }
                }],
                closed: function () {
                    $('.modals-overlay.wtai-grid-invalid-image-popup-overlay').remove();
                },
                opened: function () {
                    $('.wtai-grid-invalid-image-popup-modal .modal-footer .action-dismiss').toggle(self.proceedable());
                    $('.wtai-grid-invalid-image-popup-modal .modal-footer .wtai-action-proceed').toggle(self.proceedable());
                    $('.wtai-grid-invalid-image-popup-modal .modal-footer .wtai-action-okay').toggle(!self.proceedable());
                }
            });

            $('.wtai-grid-invalid-image-popup').removeClass('wtai-no-display');
        },

        /**
         * Generate
         *
         * @param {Object} data
         * @param {Object} settings
         *
         * @returns {void}
         */
        _generate: function (data, settings) {
            var itemsType = '',
                selections = {};
            
            console.log(data);
            if (data.params.transfer_to_magento === true || data.params.transfer_to_magento === "on") {
                notifications.addNewGenerateStatus(
                    data.selected,
                    invalidImagePopupModel.currentUser(),
                    data
                );
            } else {
                notifications.addNewFullAutomationStatus(
                    data.selected,
                    invalidImagePopupModel.currentUser(),
                    data
                );
            }
            notifications.opened(true);

            _.extend(data.params, settings || {});

            itemsType = data.excludeMode ? 'excluded' : 'selected';

            selections[itemsType] = data[itemsType];

            if (!selections[itemsType].length) {
                selections[itemsType] = false;
            }

            _.extend(selections, data.params || {});

            /* set default store filter */
            if (!selections['filters']['store_id']) {
                selections['filters']['store_id'] = this.defaultStoreId;
            }

            var url = self.generateUrl;
            if (selections.transfer_to_magento === true || selections.transfer_to_magento === "on") {
                url = self.generateFullAutomationUrl;
            }

            selections = this.removeFailedImages(selections);

            $.ajax({
                url: url,
                type: 'POST',
                data: selections,
                dataType: 'json',
                showLoader: false,
                success: function (response) {
                    if (!response.success) {
                        errorMessagesModel.messages.push(response.message);
                        notifications.statuses.remove(function (status) {
                            return status.id === notifications.tempId;
                        });
                        if (response.unauthorized) {
                            window.location.href = response.login_url;
                        }
                        if (response.reload) {
                            massactions.prototype.gridReload();
                        }
                    } else {
                        notifications.updateTempStatusId(response.api_response.requestId, notifications.tempId);
                        notifications.currentBulkRequestId(response.api_response.requestId);
                    }
                }
            });
        },

        /**
         * Remove failed images
         *
         * @param {Object} selections
         * @returns {Object}
         */
        removeFailedImages: function (selections) {
            var failedImageIds = uploadImages.failedImageIds();

            if (failedImageIds.length) {
                selections.skip_images = failedImageIds;
            }

            return selections;
        },
    });
});
