/**
 * @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/product',
    'WriteTextAI_WriteTextAI/js/model/edit',
    'WriteTextAI_WriteTextAI/js/categories/model/edit',
    'WriteTextAI_WriteTextAI/js/model/edit/keywords/keyword-analysis',
    'WriteTextAI_WriteTextAI/js/model/edit/keywords/keywords',
    'WriteTextAI_WriteTextAI/js/model/edit/keywords/progress'
], function (
    $,
    ko,
    $t,
    Component,
    _,
    productData,
    editData,
    categoriesEditData,
    keywordAnalysis,
    keywords,
    progress
) {
    'use strict';

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

    return Component.extend({
        defaults: {
            commentHidden: false,
            recordId: 0,
            storeId: 0,
            showProgress: false
        },

        isShowProgressChanged: false,
        isCommentHiddenChanged: false,

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

            self = this;

            categoriesEditData.currentCategory.subscribe(function (category) {
                this.recordId(category.categoryId);
                this.storeId(category.storeId);
            }, this);

            editData.currentProduct.subscribe(function (product) {
                this.recordId(product.productId);
                this.storeId(product.storeId);
            }, this);

            keywords.showProgress.subscribe(function (value) {
                this.showProgress(value);
            }, this);

            this.showProgress.subscribe(function (value) {
                if (!this.isShowProgressChanged) {
                    keywords.showProgress(value);
                }
            }, this);

            progress.commentHidden.subscribe(function (value) {
                this.isCommentHiddenChanged = true;
                this.commentHidden(value);
                this.isCommentHiddenChanged = false;
            }, this);

            this.commentHidden.subscribe(function (value) {
                if (!this.isCommentHiddenChanged) {
                    progress.commentHidden(value);
                }
            }, this);
        },

        /** @inheritdoc */
        initObservable: function () {
            this._super().observe([
                'storeId',
                'recordId',
                'showProgress',
                'commentHidden'
            ]);

            this.status = ko.computed(function () {
                var status = keywordAnalysis.statuses().find(function (status) {
                    return Number(status.storeId) === Number(self.storeId()) && status.recordId === self.recordId();
                });

                if (status) {
                    return status;
                }

                return {};
            }, this);

            this.progressPerc = ko.computed(function () {
                return (this.status().completed / this.status().total) * 100;
            }, this);

            this.progressText = ko.computed(function () {
                if (this.status().statusDisplay) {
                    return this.status().statusDisplay;
                }

                if (this.status().status === 'Completed') {
                    return $t('Keyword analysis currently in progress');
                }

                return keywordAnalysis.customProgressText() || $t('Keyword analysis currently in progress');
            }, this);

            this.showFailedPage = ko.computed(function () {
                return this.status().status === 'Failed' || (
                    !keywordAnalysis.optimizing() &&
                    !keywordAnalysis.isUploading() &&
                    !keywordAnalysis.optimized() &&
                    keywordAnalysis.imageUploadFailed()
                );
            }, this);

            this.showTryAgain = ko.computed(function () {
                return this.showFailedPage();
            }, this);

            this.failedText = ko.computed(function () {
                if (keywordAnalysis.optimizationFailed()) {
                    return keywordAnalysis.customOptFailedText();
                }

                return $t('The previous keyword analysis processing failed, you can restart to try again.');
            });

            this.showPipelines = ko.computed(function () {
                return !keywordAnalysis.optimizing() &&
                    !keywordAnalysis.isUploading() &&
                    keywordAnalysis.optimized() &&
                    !keywordAnalysis.optimizationFailed() &&
                    !keywordAnalysis.imageUploadFailed();
            }, this);

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

            return this;
        },

        /**
         * @returns {void}
         */
        hideComment: function () {
            this.commentHidden(true);
        },

        /**
         * @returns {void}
         */
        showComment: function () {
            this.commentHidden(false);
        },

        /**
         * Cancel optimization.
         */
        cancel: function () {
            keywordAnalysis.optimizing(false);
            keywordAnalysis.optimized(false);
            keywordAnalysis.optimizationFailed(false);
            keywordAnalysis.imageUploadFailed(false);

            var statuses = keywordAnalysis.statuses();
            keywordAnalysis.statuses(statuses.filter(function (status) {
                return Number(status.storeId) !== Number(self.storeId()) || status.recordId !== self.recordId();
            }));

            keywords.showProgress(false);
        },

        /**
         * Start optimization.
         */
        tryAgain: function () {
            keywordAnalysis.optimizing(true);
            keywordAnalysis.optimized(false);
            keywordAnalysis.optimizationFailed(false);
            keywordAnalysis.imageUploadFailed(false);

            var statuses = keywordAnalysis.statuses();
            keywordAnalysis.statuses(statuses.filter(function (status) {
                return Number(status.storeId) !== Number(self.storeId()) || status.recordId !== self.recordId();
            }));

            $.ajax({
                url: self.deleteOptimizationUrl,
                type: 'POST',
                data: {
                    record_id: self.recordId(),
                    store_id: self.storeId(),
                    entity_type: self.entityType
                },
                dataType: 'json',
                showLoader: false,
                success: function (response) {
                    if (response.success) {
                        $.ajax({
                            url: self.updateOptimizationUrl,
                            type: 'POST',
                            data: {
                                record_id: self.recordId(),
                                store_id: self.storeId(),
                                entity_type: self.entityType,
                                url: productData.productUrl(),
                                name: productData.productName(),
                                image_id: keywords.thumbnailId(),
                                /** seed_keywords: keywords.selectedKeywords(), */
                                search_intent_selected: keywords.searchIntentSelected()
                            },
                            dataType: 'json',
                            showLoader: false,
                            success: function (response) {
                                if (!response.success) {
                                    keywordAnalysis.optimizationFailed(true);
                                    keywordAnalysis.optimizing(false);
                                    keywordAnalysis.customOptFailedText(response.error);
                                }
                            }
                        });
                    }
                }
            });
        }
    });
});
