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

define([
    'jquery',
    'ko',
    'underscore',
    'Magento_Ui/js/grid/columns/actions',
    'WriteTextAI_WriteTextAI/js/model/history-log',
    'WriteTextAI_WriteTextAI/js/model/edit/product',
    'WriteTextAI_WriteTextAI/js/model/edit/keywords/keyword-analysis',
    'WriteTextAI_WriteTextAI/js/model/grid/reference-products',
    'WriteTextAI_WriteTextAI/js/model/grid/listing',
    'WriteTextAI_WriteTextAI/js/categories/model/edit',
    'WriteTextAI_WriteTextAI/js/grid/reload',
    'WriteTextAI_WriteTextAI/js/model/grid/error-messages',
    'WriteTextAI_WriteTextAI/js/utils/grid/actions',
    'WriteTextAI_WriteTextAI/js/model/grid/notifications',
    'WriteTextAI_WriteTextAI/js/model/grid/transfer-prompt',
    'mage/translate',
    'Magento_Ui/js/modal/confirm',
    'mage/validation'
], function (
    $,
    ko,
    _,
    Column,
    historyLog,
    product,
    keywordAnalysis,
    referenceProducts,
    listingModel,
    editData,
    reloadGrid,
    errorMessagesModel,
    gridUtils,
    notifications,
    transferPrompt,
    $t,
    confirm
) {
    'use strict';

    return Column.extend({
        defaults: {
            ids: [],
            users: [],
            currentUser: {},
            transferFormSelector: '#wtaiBulkTransferForm',
            listens: {
                ids: 'updateIds',
                users: 'updateUsers'
            }
        },

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

            this.currentUser.subscribe(function (currentUser) {
                if (currentUser && Object.keys(currentUser).length !== 0) {
                    listingModel.currentUser(currentUser);
                }
            }, this);
        },

        /** @inheritdoc */
        initObservable: function () {
            this._super()
                .observe([
                    'currentUser'
                ])
                .track([
                    'ids',
                    'users'
                ]);

            return this;
        },

        /** @inheritdoc */
        defaultCallback: function (
            actionIndex,
            recordId,
            action
        ) {
            var category = {
                categoryId: recordId,
                storeId: action.store_id
            };
            
            switch (actionIndex) {
                case 'edit':
                    editData.currentCategory(category);
                    product.storeId(action.store_id); /** Update store id in transfer prompt */
                    break;

                case 'transfer':
                    this.transfer(action);
                    break;
             
                default:
                    this._super(
                        actionIndex,
                        recordId,
                        action
                    );
                    break;
            }
        },

        /**
         * Update ids.
         */
        updateIds: function () {
            editData.ids(this.ids);
        },

        /**
         * Update history log users.
         */
        updateUsers: function () {
            historyLog.users(this.users);
        },

        /** @inheritdoc */
        _confirm: function (action, callback) {
            var confirmData = action.confirm,
                formSelector = this.transferFormSelector;

            if (action.index !== 'transfer') {
                this._super(action, callback);
                return;
            }

            transferPrompt.storeFilter(action.store_id);

            confirm({
                title: confirmData.title,
                content: confirmData.message,
                modalClass: 'wtai-modal wtai-bulk-transfer-popup wtai-transfer',
                actions: {
                    confirm: callback,
                    cancel: function () {
                        $('body').removeClass('_has-modal');
                    }
                },
                buttons: [{
                    text: $t('Cancel'),
                    class: 'action-secondary action-dismiss',
                    click: function (event) {
                        this.closeModal(event);
                    }
                }, {
                    text: $t('Transfer'),
                    class: 'action-primary action-accept',
                    click: function (event) {
                        if (
                            $(formSelector).data('validator') &&
                            $(formSelector).validation() &&
                            $(formSelector).validation('isValid')
                        ) {
                            this.closeModal(event, true);
                            $('body').removeClass('_has-modal');
                        }
                    }
                }]
            });
        },

        /**
         * Row transfer action.
         *
         * @param {Object} action
         * @returns {void}
         */
        transfer: function (action) {
            var selector = this.transferFormSelector,
                settings = {};

            transferPrompt.storeFilter(action.store_id);

            if ($(selector).length) {
                settings = gridUtils.convertForm($(selector));
            }

            var currentUser = (this.currentUser && typeof this.currentUser === 'function')
                ? this.currentUser()
                : {};

            _.extend(settings, {
                queue_ids: [action.record_id],
                filters: {
                    store_id: action.store_id
                },
                store_id: action.store_id,
                user: currentUser.email || ''
            });

            this.transferCategory(action.url, settings);
        },

        /**
         * Submit row transfer.
         *
         * @param {String} url
         * @param {Object} params
         * @returns {void}
         */
        transferCategory: function (url, params) {
            errorMessagesModel.messages([]);

            var currentUser = (this.currentUser && typeof this.currentUser === 'function')
                ? this.currentUser()
                : {};

            notifications.addNewSingleGridTransferStatus([
                params.queue_ids[0]
            ], currentUser);
            notifications.opened(true);

            $.ajax({
                url: url,
                type: 'POST',
                data: params,
                dataType: 'json',
                showLoader: false,
                success: function (response) {
                    if (!response.success) {
                        errorMessagesModel.messages.push(response.message);
                        notifications.statuses.remove(function (status) {
                            return status.id === notifications.transferTempId;
                        });
                        if (response.unauthorized) {
                            window.location.href = response.login_url;
                        }
                    } else {
                        this.gridReload();
                        notifications.updateTransferStatus(
                            [params.queue_ids[0]],
                            currentUser.email,
                            [],
                            [params.queue_ids[0]],
                            'Completed'
                        );
                    }
                }.bind(this)
            });
        },

        /**
         * Reload category grid.
         */
        gridReload: function () {
            var showLoader = false;
            reloadGrid.reloadUIComponent(
                'wtai_categories_grid_listing.wtai_categories_grid_listing_data_source',
                showLoader
            );
        },

        /**
         * Check if action is disabled.
         *
         * @param {Object} action
         * @returns {Boolean}
         */
        isDisabled: function (action) {
            if (action.index === 'transfer') {
                return ko.computed(function () {
                    try {
                        var status = keywordAnalysis.statuses().find(function (status) {
                            return Number(status.storeId) === Number(referenceProducts.storeId()) &&
                                Number(status.recordId) === Number(action.recordId) &&
                                status.status === 'Running';
                        });
                        
                        if (status) {
                            return true;
                        }

                        return false;
                    } catch (error) {
                        return false;
                    }
                }, this);
            }
        }
    });
});
