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

define([
    'jquery',
    'ko',
    'uiComponent',
    'underscore',
    'WriteTextAI_WriteTextAI/js/categories/model/edit',
    'WriteTextAI_WriteTextAI/js/model/edit/settings',
    'WriteTextAI_WriteTextAI/js/categories/model/edit/textfields',
    'WriteTextAI_WriteTextAI/js/model/edit/error-messages',
    'WriteTextAI_WriteTextAI/js/model/edit/transfer/settings',
    'WriteTextAI_WriteTextAI/js/model/edit/review-status',
    'WriteTextAI_WriteTextAI/js/model/edit/mark-reviewed',
    'WriteTextAI_WriteTextAI/js/utils/edit/textfields',
    'WriteTextAI_WriteTextAI/js/model/edit/keywords/keyword-analysis',
    'Magento_Ui/js/modal/confirm',
    'mage/translate'
], function (
    $,
    ko,
    Component,
    _,
    editData,
    settings,
    textfields,
    errorMessagesModel,
    transferSettings,
    reviewStatus,
    markReviewed,
    textfieldsUtils,
    keywordAnalysis,
    confirm,
    $t
) {
    'use strict';

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

    return Component.extend({
        defaults: {
            previewButtonSelector: '.wtai-preview-button',
            defaultStoreId: 0
        },

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

            self = this;

            editData.opened.subscribe(function (opened) {
                if (opened && !self.eventsInitialized) {
                    self.bindPreviewButton();
                    self.eventsInitialized = true;
                }
            });
        },

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

            this.isNotAllStoreView = ko.computed(function () {
                return parseInt(editData.currentCategory().storeId) !== this.defaultStoreId;
            }, this);

            this.guideSteps = ko.computed(function () {
                return settings.guideSteps();
            });

            this.canSave = ko.computed(function () {
                var fields = [{
                    original: textfields.originalPageTitle(),
                    edited: textfields.pageTitle()
                }, {
                    original: textfields.originalPageDescription(),
                    edited: textfields.pageDescription()
                }, {
                    original: textfields.originalCategoryDescription(),
                    edited: textfields.categoryDescription()
                }];
                return fields.some(function (field) {
                    return field.original !== field.edited;
                });
            }, this);

            this.canTransfer = ko.computed(function () {
                var statusMapping = {
                    page_title: textfields.statuses().pageTitleGenerateStatus,
                    page_description: textfields.statuses().pageDescriptionGenerateStatus,
                    category_description: textfields.statuses().categoryDescriptionGenerateStatus
                },
                    canTransferText = textfields.selectedFields().length > 0 &&
                        textfields.selectedFields().some(function (field) {
                            return statusMapping[field];
                        }),
                    isOptimizing = keywordAnalysis.statuses().find(function (status) {
                        return Number(status.storeId) === Number(editData.currentCategory().storeId) &&
                            status.recordId === editData.currentCategory().categoryId &&
                            status.status === 'Running';
                    }),
                    isCatOptimizing =
                        Number(keywordAnalysis.optimizingId()) === Number(editData.currentCategory().categoryId) &&
                        Number(keywordAnalysis.optimizingStoreId()) === Number(editData.currentCategory().storeId),
                    keywordAnalysisOngoing = (keywordAnalysis.optimizing() ||
                    keywordAnalysis.isUploading()) &&
                        !keywordAnalysis.optimized() &&
                        !keywordAnalysis.optimizationFailed() &&
                        !keywordAnalysis.imageUploadFailed();

                if (isOptimizing || (keywordAnalysisOngoing && isCatOptimizing)) {
                    return false;
                }

                return canTransferText;
            }, this);

            return this;
        },

        /**
         * Bind preview button.
         */
        bindPreviewButton: function () {
            $(this.previewButtonSelector).on('click', function () {
                var previewUrl = $(this).data('link');

                window.open(previewUrl, '_blank');
            });
        },

        /**
         * Save text to api.
         */
        save: function () {
            var url = self.saveUrl,
                changedFields = {},
                statuses = textfields.statuses();

            if (textfields.pageTitle() !== textfields.originalPageTitle() &&
                textfields.pageTitle() !== ''
            ) {
                changedFields.page_title = textfields.pageTitle();
                statuses.pageTitleTransferStatus = false;
            }
            if (textfields.pageDescription() !== textfields.originalPageDescription() &&
                textfields.pageDescription() !== ''
            ) {
                changedFields.page_description = textfields.pageDescription();
                statuses.pageDescriptionTransferStatus = false
            }
            if (textfields.categoryDescription() !== textfields.originalCategoryDescription() &&
                textfields.categoryDescription() !== ''
            ) {
                changedFields.category_description = textfields.categoryDescription();
                statuses.categoryDescriptionTransferStatus = false
            }

            errorMessagesModel.messages([]);

            $.ajax({
                url: url,
                type: 'POST',
                data: {
                    category_id: editData.currentCategory().categoryId,
                    store_id: editData.currentCategory().storeId,
                    selected_fields: changedFields
                },
                dataType: 'json',
                showWriteTextAILoader: true,
                showPageTitleLoader: true,
                showPageDescriptionLoader: true,
                showCategoryDescriptionLoader: true,
                success: function (response) {
                    if (response.success) {
                        markReviewed.reviewed(false);
                        textfields.originalPageTitle(textfields.pageTitle());
                        textfields.originalPageDescription(textfields.pageDescription());
                        textfields.originalCategoryDescription(textfields.categoryDescription());
                        textfields.statuses(statuses);
                    } else {
                        errorMessagesModel.messages.push(response.message);
                    }
                }
            });
        },

        /**
         * Transfer text to Magento.
         */
        transfer: function () {
            confirm({
                title: $.mage.__('Transfer selected to Magento'),
                content: self.confirmContent,
                modalClass: 'wtai-modal wtai-bulk-transfer-popup wtai-transfer wtai-edit',
                actions: {
                    confirm: function () {
                        self._transfer();
                    }
                },
                buttons: [{
                    text: $t('Cancel'),
                    class: 'action-secondary action-dismiss',
                    click: function (event) {
                        this.closeModal(event);
                    }
                }, {
                    text: $t('OK'),
                    class: 'action-primary action-accept',
                    click: function (event) {
                        if (
                            $('#wtaiEditTransferForm').data('validator') &&
                            $('#wtaiEditTransferForm').validation() &&
                            $('#wtaiEditTransferForm').validation('isValid')
                        ) {
                            this.closeModal(event, true);
                        }
                    }
                }]
            });
        },

        /**
         * Transfer text to Magento.
         */
        _transfer: function () {
            var url = self.transferUrl,
                selectedFields = {},
                mapping = {
                    page_title: textfields.pageTitle(),
                    page_description: textfields.pageDescription(),
                    category_description: textfields.categoryDescription()
            };

            errorMessagesModel.messages([]);

            textfields.selectedFields().forEach(function (field) {
                selectedFields[field] = mapping[field];
            });

            $.ajax({
                url: url,
                type: 'POST',
                data: {
                    category_id: editData.currentCategory().categoryId,
                    store_id: editData.currentCategory().storeId,
                    selected_fields: selectedFields,
                    selected_stores: transferSettings.selectedStores()
                },
                dataType: 'json',
                showWriteTextAILoader: true,
                showPageTitleLoader: textfields.selectedFields().includes('page_title'),
                showPageDescriptionLoader: textfields.selectedFields().includes('page_description'),
                showCategoryDescriptionLoader: textfields.selectedFields().includes('category_description'),
                success: function (response) {
                    if (response.success) {
                        var fields = response.fields;
                        if (response.use_default) {
                            textfields.useDefault({
                                pageTitle: textfields.selectedFields().includes('page_title') ?
                                    response.use_default.page_title : textfields.useDefault().pageTitle,
                                pageDescription: textfields.selectedFields().includes('page_description') ?
                                    response.use_default.page_description : textfields.useDefault().pageDescription,
                                categoryDescription: textfields.selectedFields().includes('category_description') ?
                                    response.use_default.category_description : textfields.useDefault().categoryDescription
                            });
                        }
                        markReviewed.reviewed(response.reviewed);
                        if (transferSettings.selectedStores().map(String).includes(String(editData.currentCategory().storeId))) {
                            textfieldsUtils.updateCategoryCurrentFields(fields, textfields.selectedFields(), {
                                'page_title': textfields.pageTitle(),
                                'page_description': textfields.pageDescription(),
                                'category_description': textfields.categoryDescription()
                            });
                        }
                        reviewStatus.reviewStatus(response.updatedReview);
                    } else {
                        errorMessagesModel.messages.push(response.message);
                    }
                }
            });
        }
    });
});
