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

define([
    'jquery',
    'uiComponent',
    'underscore',
    'ko',
    'mage/translate',
    '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/keyword-pipelines',
    'WriteTextAI_WriteTextAI/js/edit/keywords/keyword-pipelines/pipeline-keyword',
    'WriteTextAI_WriteTextAI/js/edit/keywords/keyword-pipelines/edit-pipeline',
    'WriteTextAI_WriteTextAI/js/model/edit/error-messages'
], function (
    $,
    Component,
    _,
    ko,
    $t,
    editData,
    categoriesEditData,
    keywordAnalysisData,
    keywordPipelinesData,
    pipelineKeyword,
    editPipeline,
    errorMessagesModel
) {
    'use strict';

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

    return Component.extend({
        defaults: {
            test: 'test',
            editKeywordRankingVisible: false,
            editKeywordRankingItems: [],
            storeId: 0,
            recordId: 0,
        },

        gettingData: null,

        /** @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);

            this.editKeywordRankingVisible.subscribe(function (editKeywordRankingVisible) {
                keywordAnalysisData.editKeywordRankingVisible(editKeywordRankingVisible);
            }, this);

            this.editKeywordRankingItems.subscribe(function (editKeywordRankingItems) {
                keywordAnalysisData.editKeywordRankingItems(editKeywordRankingItems);
            }, this);

            keywordPipelinesData.editKeywordRankingVisible.subscribe(function (editKeywordRankingVisible) {
                this.editKeywordRankingVisible(editKeywordRankingVisible);
                if (!editKeywordRankingVisible) {
                    this.editKeywordRankingItems([]);
                }
            }, this);
        },

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

            this.rankingKeywords = ko.computed(function () {
                var optimizationData = keywordAnalysisData.optimizationData();
                if (!optimizationData || !optimizationData.rankingKeywords) {
                    return [];
                }
                var keywords = optimizationData.rankingKeywords || [];
                return keywords.length > 5 ? keywords.slice(0, 5) : keywords;
            }, this);

            this.ranges = ko.computed(function () {
                return keywordAnalysisData.optimizationData().ranges;
            });

            this.saveDisabled = ko.computed(function () {
                const items = this.editKeywordRankingItems();
                if (items.length === 0) {
                    return true;
                }

                var hasRemoved = items.some(function (keyword) {
                    return keyword.removed;
                });

                return !hasRemoved;
            }, this);

            this.getPrimaryKeyword = ko.computed(function () {
                if (keywordAnalysisData.optimizationData() &&
                    keywordAnalysisData.optimizationData().optimizingKeywords &&
                    keywordAnalysisData.optimizationData().optimizingKeywords.length > 0) {
                    return keywordAnalysisData.optimizationData().optimizingKeywords[0];
                }
                return null;
            }, this);

            return this;
        },

        /**
         * Get difficulty
         *
         * @param {string} difficulty
         * @returns {string}
         */
        getDifficulty: function (difficulty) {
            return editPipeline.getDifficulty(self, difficulty, true);
        },

        /**
         * Edit keyword ranking.
         */
        editKeywordRanking: function () {
            self.editKeywordRankingVisible(true);
            self.editKeywordRankingItems([]);
            const keywords = JSON.parse(JSON.stringify(keywordAnalysisData.optimizationData().rankingKeywords));
            self.editKeywordRankingItems(keywords);
        },

        /**
         * Close edit keyword ranking.
         */
        closeEditKeywordRanking: function () {
            self.editKeywordRankingVisible(false);
            self.editKeywordRankingItems([]);
        },

        /**
         * Remove keyword.
         *
         * @param {number} index
         */
        removeKeyword: function (index) {
            const items = self.editKeywordRankingItems();
            let keywordToDelete = items[index];
            let keywordPool = keywordAnalysisData.optimizationData().keywords;
            if (!keywordPool.some(keyword => keyword.keyword === keywordToDelete.keyword)) {
                if (keywordToDelete.keyword !== '' && keywordToDelete.manual !== true) {
                    keywordPool.push(keywordToDelete);
                }
            }
            items[index].removed = true;
            self.editKeywordRankingItems([]);
            self.editKeywordRankingItems(items);
        },

        /**
         * Is primary keyword
         *
         * @param {string} keyword
         *
         * @returns {boolean}
         */
        isPrimaryKeyword: function (keyword) {
            return self.getPrimaryKeyword() === keyword;
        },

        /**
         * Save edit keyword ranking.
         */
        saveEditKeywordRanking: function () {
            const items = self.editKeywordRankingItems();
            var removedKeywords = items.filter(function (keyword) {
                return keyword.removed;
            }).map(function (keyword) {
                return keyword.keyword;
            });
            
            $.ajax({
                url: self.saveEditKeywordRankingUrl,
                type: 'POST',
                data: {
                    'store_id': self.storeId(),
                    'record_id': self.recordId(),
                    'entity_type': self.entityType,
                    'keywords_to_remove': removedKeywords
                },
                dataType: 'json',
                showWriteTextAILoader: true,
                showEditPipelineLoader: true,
                success: function (response) {
                    if (response.success) {
                        let updatedOptimizationData = JSON.parse(JSON.stringify(response.optimization_data));
                        keywordAnalysisData.optimizationData(updatedOptimizationData);
                        keywordAnalysisData.snapshotData(updatedOptimizationData.snapshots || {});
                        self.closeEditKeywordRanking();
                    } else {
                        if (typeof response.error !== 'undefined') {
                            errorMessagesModel.messages.push(response.error);
                        }
                    }
                }
            });
        },

        /**
         * Get converted serp date text
         *
         * @param {Object} self
         * @param {string} difficulty
         * @param {string} keywords
         *
         * @returns {string}
         */
        getSerpDateText: function (rawDate) {
            var dateFormat = rawDate || new Date();
            var datePrepare = new Date(dateFormat)
            var formatDate = new Intl.DateTimeFormat('en-US', {
                year: 'numeric',
                month: 'long',
                day: 'numeric',
                hour: '2-digit',
                minute: '2-digit',
                hour12: false,
                timeZone: self.timezone
            }).format(datePrepare);
            formatDate = formatDate.replace(' at ', ' ').trim();
            return $t('SERP data as of %s').replace('%s', formatDate)
        },

        /**
         * Get keyword title
         *
         * @param {Object} keywordData
         *
         * @returns {string}
         */
        getKeywordTitle: function (keywordData) {
            var isPrimary = keywordData.keyword === self.getPrimaryKeyword();
            var isRanking = keywordData.position > 0;
            if (isPrimary && isRanking) {
                return $t('Primary keyword and ranking in the SERP');
            }
            if (isPrimary) {
                return $t('Primary keyword');
            }
            if (isRanking) {
                return $t('Ranking in the SERP');
            }
            return '';
        }
    });
});
