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

define([
    'jquery',
    'uiComponent',
    'underscore',
    'WriteTextAI_WriteTextAI/js/model/edit',
    'WriteTextAI_WriteTextAI/js/model/edit/product',
    'WriteTextAI_WriteTextAI/js/categories/model/edit',
    'WriteTextAI_WriteTextAI/js/categories/model/edit/category',
    'WriteTextAI_WriteTextAI/js/model/edit/keywords/keyword-analysis',
    'WriteTextAI_WriteTextAI/js/model/edit/keywords/keywords',
    'WriteTextAI_WriteTextAI/js/edit/keywords/keywords',
    'WriteTextAI_WriteTextAI/js/model/edit/keywords/error-messages',
    'WriteTextAI_WriteTextAI/js/model/edit/audience',
    'ko',
    'mage/translate',
    'Magento_Ui/js/modal/modal'
], function (
    $,
    Component,
    _,
    editData,
    productData,
    categoriesEditData,
    categoryData,
    keywordAnalysis,
    keywords,
    keywordsComponent,
    errorMessagesModel,
    audience,
    ko,
    $t
) {
    'use strict';

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

    return Component.extend({
        defaults: {
            showLoader: false,
            historyMode: false,
            historySelectedDatetime: '',
            recordId: 0,
            storeId: 0,
            recordUrl: '',
            recordName: '',
            refreshingData: false,
            modal: {
                contentSelector: '.wtai-keyword-analysis'
            },
            selectors: {
                tooltipSelector:
                    '.wtai-edit-keyword-analysis .admin__field-tooltip-action',
                calendar: '.wtai-calendar'
            },
            showGoToBottom: false,
            isRefreshingDataUserChanged: false
        },

        gettingData: false,

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

            self = this;

            this.initTooltip();

            const el = document.querySelector('.wtai-keyword-analysis-content');
            if (el) {
                $('.wtai-keyword-analysis-content > *').applyBindings(this);
            }

            keywordAnalysis.optimizationData.subscribe(function (optimizationData) {
                if (Object.keys(optimizationData).length > 0) {
                    switch (optimizationData.status) {
                        case 'Manual':
                            keywordAnalysis.optimizing(false);
                            keywordAnalysis.optimized(false);
                            keywordAnalysis.optimizationFailed(false);
                            break;
                        case 'Failed':
                            keywordAnalysis.optimizing(false);
                            keywordAnalysis.optimized(false);
                            keywordAnalysis.optimizationFailed(true);
                            break;
                        case 'Pending':
                        case 'InProgress':
                            keywordAnalysis.optimized(false);
                            keywordAnalysis.optimizing(true);
                            keywordAnalysis.optimizationFailed(false);
                            break;
                        case 'Completed':
                            keywordAnalysis.optimizing(false);
                            keywordAnalysis.optimized(true);
                            keywordAnalysis.optimizationFailed(false);
                            break;
                        default:
                            keywordAnalysis.optimizing(false);
                            keywordAnalysis.optimized(false);
                            keywordAnalysis.optimizationFailed(false);
                            break;
                    }
                } else {
                    keywordAnalysis.optimizing(false);
                    keywordAnalysis.optimized(false);
                    keywordAnalysis.optimizationFailed(false);
                }
            });

            this.status.subscribe(function (status) {
                var isProductOpened = status.recordId === this.recordId() &&
                    Number(status.storeId) === Number(this.storeId());

                if (status.status === 'Completed' && keywords.showProgress()) {
                    if (!isProductOpened) {
                        keywords.showProgress(false);
                        return;
                    }
                    if (!keywordAnalysis.autoGenerateOrRewriteChecked() || keywords.noGenerateOnAutoGenerateAfterKo()) {
                        this.getOptimization();
                    }
                }
            }, this);

            keywordAnalysis.historyMode.subscribe(function (historyMode) {
                self.historyMode(historyMode);
            });

            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);

            productData.productUrl.subscribe(function (productUrl) {
                this.recordUrl(productUrl);
            }, this);

            productData.productName.subscribe(function (productName) {
                this.recordName(productName);
            }, this);

            categoryData.categoryUrl.subscribe(function (categoryUrl) {
                this.recordUrl(categoryUrl);
            }, this);

            categoryData.categoryName.subscribe(function (categoryName) {
                this.recordName(categoryName);
            }, this);

            keywordAnalysis.currentlySelectedSnapshot.subscribe(function (snapshot) {
                let datePrepare = new Date(snapshot.date);
                /** TODO: Make language dynamic when enabling translations */
                let convertedDate = new Intl.DateTimeFormat('en-US', {
                    year: 'numeric',
                    month: 'long',
                    day: 'numeric',
                    hour: '2-digit',
                    minute: '2-digit',
                    hour12: false,
                    timeZone: self.timezone
                }).format(datePrepare);
                convertedDate = convertedDate.replace(' at ', ' ').trim();
                this.historySelectedDatetime(convertedDate);
            }, this);

            keywordAnalysis.refreshingData.subscribe(function (refreshingData) {
                if (self.isRefreshingDataUserChanged) {
                    return;
                }
                self.refreshingData(refreshingData);
            }, this);
                
            self.refreshingData.subscribe(function (refreshingData) {
                self.isRefreshingDataUserChanged = true;
                keywordAnalysis.refreshingData(refreshingData);
                self.isRefreshingDataUserChanged = false;
            }, this);
        },

        /** @inheritdoc */
        initObservable: function () {
            this._super().observe([
                'showLoader',
                'historySelectedDatetime',
                'recordId',
                'storeId',
                'recordUrl',
                'recordName',
                'historyMode',
                'refreshingData',
                'showGoToBottom'
            ]);

            $('.wtai-edit-keyword-analysis .modal-content').on('scroll', function () {
                const modalContent = $('.wtai-edit-keyword-analysis .modal-content');
                
                if (!modalContent.length) {
                    self.showGoToBottom(false);
                    return;
                }
                
                const scrollHeight = modalContent[0].scrollHeight;
                const scrollTop = modalContent.scrollTop();
                const clientHeight = modalContent.height();
                
                /** Show button if not scrolled to bottom (leaving 20px threshold) */
                const showGoToBottom = scrollHeight - (scrollTop + clientHeight) > 20;

                self.showGoToBottom(showGoToBottom);
            });

            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.showLoadingPage = ko.computed(function () {
                return (keywordAnalysis.optimizing() ||
                    keywordAnalysis.isUploading()) &&
                    !keywordAnalysis.optimized() &&
                    !keywordAnalysis.optimizationFailed() &&
                    !keywordAnalysis.imageUploadFailed();
            }, this);

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

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

            this.showBack = ko.computed(function () {
                return (keywordAnalysis.optimizing() ||
                    keywordAnalysis.optimized()) &&
                    !keywordAnalysis.isUploading() &&
                    !keywordAnalysis.optimizationFailed() &&
                    !keywordAnalysis.imageUploadFailed();
            }, 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;
                }
                
                return keywordAnalysis.customProgressText();
            }, this);

            this.language = ko.computed(function () {
                return keywords.language();
            });

            this.country = ko.computed(function () {
                return keywords.country();
            });

            this.lastUpdated = ko.computed(function () {
                if (!keywordAnalysis.snapshotData()) {
                    return '';
                }
                if (keywordAnalysis.snapshotData()[0] === undefined) {
                    return '';
                }
                const latestItem = keywordAnalysis.snapshotData().reduce((latest, current) => {
                    return new Date(current.date) > new Date(latest.date) ? current : latest;
                });
                let datePrepare = new Date(latestItem.date);
                /** TODO: Make language dynamic when enabling translations */
                let convertedDate = new Intl.DateTimeFormat('en-US', {
                    year: 'numeric',
                    month: 'long',
                    day: 'numeric',
                    hour: '2-digit',
                    minute: '2-digit',
                    hour12: false,
                    timeZone: self.timezone
                }).format(datePrepare);
                convertedDate = convertedDate.replace(' at ', ' ').trim();
                return $t('Last updated %1').replace('%1', convertedDate);
            });

            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.showProceed = ko.computed(function () {
                return keywordAnalysis.imageUploadFailed();
            });

            this.showTryAgain = ko.computed(function () {
                return keywordAnalysis.optimizationFailed();
            });

            this.hideRefreshNow = ko.computed(function () {
                return this.refreshingData() || keywordAnalysis.historyMode();
            }, this);

            return this;
        },

        /**
         * Go to bottom.
         */
        goToBottom: function () {
            $('.wtai-edit-keyword-analysis .modal-content').animate(
                { scrollTop: $('.wtai-edit-keyword-analysis .modal-content').height() }
                ,
                1000
            );
        },

        /**
         * Proceed to AI powered request.
         */
        proceed: function () {
            keywords.showProgress(true);
            keywordAnalysis.optimizing(true);
            keywordAnalysis.isUploading(false);
            keywordAnalysis.optimized(false);
            keywordAnalysis.optimizationFailed(false);
            keywordAnalysis.imageUploadFailed(false);
            keywordAnalysis.customOptFailedText('');
            keywordAnalysis.customProgressText($t('Queued for keyword analysis'));
            keywordsComponent.prototype.startAIpoweredRequest();
        },

        /**
         * Initialize edit modal tooltips.
         */
        initTooltip: function () {
            $(self.selectors.tooltipSelector).dropdown({
                parent: '.admin__field-tooltip',
                autoclose: true
            });
        },

        /**
         * Close keyword analysis modal.
         */
        closeAnalysis: function () {
            
            if (keywordAnalysis.historyMode()) {
                var self = this;
                self.exitHistoryMode().then(function () {
                    $(self.modal.contentSelector).modal('closeModal');
                });
            } else {
                $(this.modal.contentSelector).modal('closeModal');
            }
            var errorMessages = errorMessagesModel.messages();
            if (errorMessages.length > 0) {
                errorMessagesModel.messages([]);
            }
        },

        /**
         * Exit history mode.
         */
        exitHistoryMode: function () {
            $('body').loader('show');

            return new Promise(function (resolve) {
                setTimeout(function () {
                    var currentOptmizationData = keywordAnalysis.storeCurrentOptimizationData();
                    keywordAnalysis.optimizationData({});
                    keywordAnalysis.optimizationData(currentOptmizationData);
                    keywordAnalysis.historyMode(false);
                    keywordAnalysis.storeCurrentOptimizationData({});
                    $(self.selectors.calendar).datepicker("setDate", null);
                    $('body').loader('hide');
                    resolve();
                }, 500);
            });
        },

        /**
         * Get optimization.
         *
         * @param {boolean} showLoader
         * @returns {void}
         */
        getOptimization: function (showLoader = false) {
            if (self.gettingData) {
                return;
            }

            self.gettingData = true;
            self.showLoader(showLoader);
            $.ajax({
                url: self.getOptimizationUrl,
                type: 'POST',
                data: {
                    store_id : self.storeId(),
                    record_id: self.recordId(),
                    entity_type: self.entityType
                },
                dataType: 'json',
                showLoader: false,
                success: function (response) {
                    keywordAnalysis.optimizing(false);
                    keywordAnalysis.optimized(true);
                    keywordAnalysis.optimizationData(response.api_response);
                    keywordAnalysis.snapshotData(response.api_response.snapshots || {});
                    
                    var selKeywords = [];
                    if (response.api_response.optimizingKeywords
                        && response.api_response.optimizingKeywords.length > 0) {
                        selKeywords = response.api_response.optimizingKeywords;
                    } else {
                        selKeywords = response.api_response.manualKeywords;
                    }
                    self.showLoader(false);
                    self.gettingData = false
                }
            }).always(function () {
                keywords.showProgress(false);

                if ((!keywordAnalysis.autoGenerateOrRewriteChecked() || keywords.noGenerateOnAutoGenerateAfterKo()) &&
                    $('.wtai-edit-modal.wtai-edit-main').hasClass('_show')
                ) {
                    keywordsComponent.prototype.openModal();
                }
            });
        },

        /**
         * Create snaphot request
         */
        createSnapshotRequest: function () {
            self.refreshingData(true);
            $.ajax({
                url: self.createSnapshotUrl,
                type: 'POST',
                data: {
                    record_id: self.recordId(),
                    store_id: self.storeId(),
                    entity_type: self.entityType
                },
                dataType: 'json',
                showLoader: false,
                success: function (response) {
                    let optimizationData = keywordAnalysis.optimizationData();
                    if (response.success === true) {
                        if (response.api_response.data) {
                            let responseData = response.api_response.data;
                            keywordAnalysis.optimizationData({});
                            keywordAnalysis.optimizationData(responseData);
                            keywordAnalysis.optimizationData(optimizationData);
                        }
                        keywordAnalysis.historyMode(false);
                    } else {
                        self.refreshingData(false);
                        keywordAnalysis.historyMode(false);
                        if (response.error) {
                            errorMessagesModel.messages.push(response.error);
                        }
                    }
                }
            });
        },

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

        /**
         * Regenerate suggested audience.
         *
         * @param {Array} keywords
         * @param {String} productName
         */
        getAudience: function (keywords, productName) {
            var url = self.audienceGetUrl,
                storeId = self.storeId(),
                recordId = self.recordId();
            var data = {
                product_id: recordId,
                store_id: storeId,
                keywords: keywords,
                product_name: productName
            }
            if (self.entityType === 'Category') {
                url = self.audienceGetUrlCategories;
                data = {
                    category_id: recordId,
                    store_id: storeId,
                    keywords: keywords,
                    category_name: productName
                }
            }

            $.ajax({
                url: url,
                type: 'POST',
                data: data,
                dataType: 'json',
                showWriteTextAILoader: true,
                showAudienceLoader: true,
                success: function (response) {
                    if (response.success) {
                        audience.selectedAudience(response.selected.shift());
                        audience.suggestedAudience(response.values);
                    }
                }
            });
        },
    });
});
