/**
 * @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/edit/mark-reviewed',
    'WriteTextAI_WriteTextAI/js/model/edit/generate/keyword-analysis',
    'WriteTextAI_WriteTextAI/js/model/edit/keywords/keyword-analysis',
    'WriteTextAI_WriteTextAI/js/model/signalr',
    'WriteTextAI_WriteTextAI/js/utils/edit/generate',
    'WriteTextAI_WriteTextAI/js/edit/buttons',
    'WriteTextAI_WriteTextAI/js/model/edit/invalid-image-popup',
    'WriteTextAI_WriteTextAI/js/model/edit/gallery',
    'WriteTextAI_WriteTextAI/js/model/edit/error-messages',
    'WriteTextAI_WriteTextAI/js/model/edit/keywords/keywords',
    "Magento_Ui/js/modal/modal"
], function (
    $,
    ko,
    $t,
    Component,
    _,
    markReviewed,
    genKeywordAnalysis,
    keywordAnalysis,
    signalRModel,
    generateUtils,
    buttonsComponent,
    invalidImagePopupModel,
    gallery,
    errorMessagesModel,
    keywords
) {
    'use strict';

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

    return Component.extend({
        defaults: {
            generateParams: {},
            saveUrl: '',
            doNotShowAgainValue: false
        },

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

            self = this;

            const el = document.querySelector('.wtai-invalid-image-popup');
            if (el) {
                ko.applyBindings(this, el);
            }

            this.initModal();

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

        /** @inheritdoc */
        initObservable: function () {
            this._super()
                .observe([
                    'generateParams'
                ]);

            this.doNotShowAgain = ko.observable(!!this.doNotShowAgainValue);
            invalidImagePopupModel.doNotShowAgain(!!this.doNotShowAgainValue);

            this.doNotShowAgain.subscribe(function (val) {
                invalidImagePopupModel.doNotShowAgain(!!val);
            }, this);
            
            this.proceedable = ko.computed(function () {
                return gallery.proceedable();
            }, this);

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

            this.optimizing = ko.computed(function () {
                return keywordAnalysis.imageUploadFailed();
            }, this);

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

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

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

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

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

            return this;
        },

        /**
         * Initialize modal
         */
        initModal: function () {
            $('.wtai-invalid-image-popup').modal({
                type: 'popup',
                responsive: true,
                title: $t('Some images could not be processed:'),
                modalClass: 'wtai-invalid-image-popup-modal',
                overlayClass: 'modals-overlay wtai-invalid-image-popup-overlay',
                buttons: [{
                    text: $t('Cancel'),
                    class: 'action-secondary action-dismiss',
                    click: function () {
                        self.doNotShowAgain(!!self.doNotShowAgainValue);
                        keywordAnalysis.optimizing(false);
                        keywordAnalysis.isUploading(false);
                        keywordAnalysis.imageUploadFailed(false);
                        this.closeModal();
                    }
                }, {
                    text: $t('Proceed'),
                    class: 'action-primary wtai-action-proceed',
                    click: function () {
                        keywordAnalysis.imageUploadFailed(false);
                        if (invalidImagePopupModel.keywordAnalysis()) {
                            keywords.showProgress(true);
                        }
                        window.wtaiInvalidImagePopupDoNotShowAgain = !!self.doNotShowAgain();
                        self.doNotShowAgainValue = !!self.doNotShowAgain();
                        if(self.doNotShowAgainValue){
                            self.saveDoNotShowAgainSetting(self.doNotShowAgain());
                        }
                        self._generate(self.generateParams(), invalidImagePopupModel.keywordAnalysis());
                        this.closeModal();
                    }
                }, {
                    text: $t('Okay'),
                    class: 'action-primary wtai-action-okay',
                    click: function () {
                        this.closeModal();
                    }
                }],
                closed: function () {
                    self.doNotShowAgain(!!self.doNotShowAgainValue);
                    keywordAnalysis.optimizing(false);
                    keywordAnalysis.isUploading(false);
                    keywordAnalysis.imageUploadFailed(false);
                    $('.modals-overlay.wtai-invalid-image-popup-overlay').remove();
                },
                opened: function () {
                    $('.wtai-invalid-image-popup-modal .modal-footer .action-dismiss').toggle(gallery.proceedable());
                    $('.wtai-invalid-image-popup-modal .modal-footer .wtai-action-proceed').toggle(gallery.proceedable());
                    $('.wtai-invalid-image-popup-modal .modal-footer .wtai-action-okay').toggle(!gallery.proceedable());

                    var $modal = $('.wtai-invalid-image-popup-modal');
                    var $footer = $modal.find('.modal-footer');
                    var $doNotShow = $modal.find('.wtai-do-not-show-again');

                    if ($doNotShow.length && $footer.find('.wtai-do-not-show-again').length === 0) {
                        $doNotShow.detach().prependTo($footer);
                    }
                }
            });
        },

        /**
         * Save "Do not show again" setting
         *
         * @param {boolean} val
         */
        saveDoNotShowAgainSetting: function (val) {
            if (!this.saveUrl) {
                return;
            }

            $.ajax({
                url: this.saveUrl,
                type: 'POST',
                dataType: 'json',
                showWriteTextAILoader: false,
                data: {
                    form_key: window.FORM_KEY,
                    invalid_image_popup_do_not_show_again: !!val,
                    entity_type: '',
                    scope: 'edit'
                },
                success: function (response) {
                    if (!response.success) {
                        console.log(response.message);
                    }
                }
            });
        },

        /**
         * Generate
         *
         * @param {Object} data
         * @param {boolean} keywordAnalysis
         *
         * @returns {void}
         */
        _generate: function (data, keywordAnalysis = false) {
            /* do not rewrite empty fields */
            if (data.rewrite) {
                data.selected_fields = generateUtils.removeEmptyFields(
                    data.selected_fields
                );
            }
            
            if (keywordAnalysis && generateUtils.checkIfFieldsAndImagesAreEmpty(data)) {
                keywords.noGenerateOnAutoGenerateAfterKo(true);
                generateUtils.requestKeywordAnalysis(self.updateOptimizationUrl, 'Product');
                return;
            }

            /* empty text fields */
            generateUtils.clearFields(data.selected_fields, data.selected_images);

            /* remove error messages */
            errorMessagesModel.messages([]);

            data.failed_images = gallery.failedImages();

            $.ajax({
                url: self.generateUrl,
                type: 'POST',
                data: data,
                dataType: 'json',
                showWriteTextAILoader: true,
                showPageTitleLoader: data.selected_fields.includes('page_title'),
                showPageDescriptionLoader: data.selected_fields.includes('page_description'),
                showProductDescriptionLoader: data.selected_fields.includes('product_description'),
                showShortDescriptionLoader: data.selected_fields.includes('short_product_description'),
                showOpenGraphLoader: data.selected_fields.includes('open_graph'),
                showGalleryLoader: data.selected_images.length > 0,
                success: function (response) {
                    if (response.success) {
                        markReviewed.reviewed(response.reviewed);
                        genKeywordAnalysis.views(0);
                    } else {
                        buttonsComponent.prototype.getGenerated(data.selected_fields);
                        if (response.message) {
                            errorMessagesModel.messages.push(response.message);
                        }
                        signalRModel.generating(false);

                        if (response.unauthorized) {
                            window.location.href = response.login_url;
                        }
                    }
                }
            });
        }
    });
});
