/**
 * @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/edit',
    'WriteTextAI_WriteTextAI/js/model/history-log',
    '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/edit/keywords/keyword-analysis',
    'WriteTextAI_WriteTextAI/js/model/grid/reference-products',
    'mage/translate',
    'Magento_Ui/js/modal/confirm',
    'mage/validation'
], function (
    $,
    ko,
    _,
    Column,
    editData,
    historyLog,
    reloadGrid,
    errorMessagesModel,
    gridUtils,
    notifications,
    keywordAnalysis,
    referenceProducts,
    $t,
    confirm
) {
    'use strict';

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

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

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

            return this;
        },

        /** @inheritdoc */
        defaultCallback: function (
            actionIndex,
            recordId,
            action
        ) {
            var product = {
                productId: recordId,
                storeId: action.store_id
            };
            
            switch (actionIndex) {
                case 'edit':
                    editData.currentProduct(product);
                    break;

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

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

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

            _.extend(settings, {
                record_id: action.record_id,
                store_id: action.store_id
            });

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

        /**
         * Transfer product.
         *
         * @param {String} url
         * @param {Object} params
         *
         * @returns {void}
         */
        transferProduct: function (url, params) {
            errorMessagesModel.messages([]);
            notifications.addNewSingleGridTransferStatus(
                [params.record_id],
                this.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;
                        });
                    } else {
                        this.gridReload();
                        console.log('transfer success');
                        notifications.updateTransferStatus(
                            [params.record_id],
                            this.currentUser.email,
                            [],
                            [params.record_id],
                            'Completed'
                        );
                    }
                }.bind(this)
            });
        },

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

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

            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: action.label,
                    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');
                        }
                    }
                }]
            });
        },

        /**
         * Reload grid.
         */
        gridReload: function () {
            var showLoader = false;

            reloadGrid.reloadUIComponent(
                'wtai_products_grid_listing.wtai_products_grid_listing_data_source',
                showLoader
            );
        },

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

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

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