/**
 * @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/categories/edit/buttons',
    'WriteTextAI_WriteTextAI/js/categories/model/edit/invalid-image',
    'WriteTextAI_WriteTextAI/js/categories/model/edit/category',
    'WriteTextAI_WriteTextAI/js/model/edit/invalid-image-popup',
    'WriteTextAI_WriteTextAI/js/model/edit/keywords/keyword-analysis',
    'WriteTextAI_WriteTextAI/js/model/edit/keywords/keywords',
    "Magento_Ui/js/modal/modal"
], function (
    $,
    ko,
    $t,
    Component,
    _,
    buttonsComponent,
    invalidImageModel,
    category,
    invalidImagePopupModel,
    keywordAnalysis,
    keywords
) {
    'use strict';

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

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

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

            self = this;

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

            this.initModal();
        },

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

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

            this.doNotShowAgain.subscribe(function (val) {
                invalidImagePopupModel.doNotShowAgain(!!val);
            }, this);

            this.failedImages = ko.computed(function () {
                var imageUrls = [];

                if (!invalidImageModel.categoryImage()) {
                    imageUrls.push(category.image());
                }

                _.each(invalidImageModel.products().failed, function (product) {
                    imageUrls.push(product.image);
                });

                return imageUrls;
            });

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

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

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

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

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

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

            return this;
        },

        /**
         * Initialize modal
         */
        initModal: function () {
            $('.wtai-categories-invalid-image-popup').modal({
                type: 'popup',
                responsive: true,
                title: $t('Some images could not be processed:'),
                modalClass: 'wtai-categories-invalid-image-popup-modal',
                overlayClass: 'modals-overlay wtai-categories-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',
                    click: function () {
                        keywordAnalysis.imageUploadFailed(false);
                        if (invalidImageModel.keywordAnalysis()) {
                            keywords.showProgress(true);
                        }
                        window.wtaiInvalidImagePopupDoNotShowAgain = !!self.doNotShowAgain();
                        self.doNotShowAgainValue = !!self.doNotShowAgain();
                        if (self.doNotShowAgainValue) {
                            self.saveDoNotShowAgainSetting(self.doNotShowAgain());
                        }
                        buttonsComponent.prototype._generate(invalidImageModel.isRewrite(), invalidImageModel.keywordAnalysis());
                        this.closeModal();
                    }
                }],
                closed: function () {
                    self.doNotShowAgain(!!self.doNotShowAgainValue);
                    keywordAnalysis.optimizing(false);
                    keywordAnalysis.isUploading(false);
                    keywordAnalysis.imageUploadFailed(false);
                    $('.modals-overlay.wtai-categories-invalid-image-popup-overlay').remove();
                }
                ,
                opened: function () {
                    var $modal = $('.wtai-categories-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);
                    }
                }
            });
        },
    });
});
