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

define([
    'jquery',
    'uiComponent',
    'underscore',
    'WriteTextAI_WriteTextAI/js/model/edit/attributes',
    'WriteTextAI_WriteTextAI/js/model/edit/generate/attributes',
    'WriteTextAI_WriteTextAI/js/model/edit/product',
    'mage/translate',
    'mage/template',
    'text!Magento_Ui/templates/grid/cells/thumbnail/preview.html',
    'Magento_Ui/js/modal/modal'
], function (
    $,
    Component,
    _,
    attributes,
    generateAttributes,
    product,
    $t,
    mageTemplate,
    thumbnailPreviewTemplate
) {
    'use strict';

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

    return Component.extend({
        defaults: {
            productId: '',
            storeId: '',
            productAttributes: [],
            productAttributesSelected: [],
            otherProductDetails: '',
            otherProductDetailsChecked: false,
            selectAllValue: null,
            canUpdate: true,
            allAttributes: [],
            productAttributesSelectedNotPremium: []
        },

        productDetailsAllowed: false,
        isAttributesChanged: false,
        typingTimer: null,

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

            self = this;

            product.productId.subscribe(function (productId) {
                self.productId(productId);
            });

            product.storeId.subscribe(function (storeId) {
                self.storeId(storeId);
            });

            attributes.otherProductDetails.subscribe(
                function (otherProductDetails) {
                    self.isAttributesChanged = true;
                    self.otherProductDetails(otherProductDetails);
                    self.isAttributesChanged = false;
                }
            );

            attributes.otherProductDetailsChecked.subscribe(
                function (otherProductDetailsChecked) {
                    self.isAttributesChanged = true;
                    self.otherProductDetailsChecked(
                        otherProductDetailsChecked
                    );
                    self.isAttributesChanged = false;
                }
            );

            attributes.productAttributesSelected.subscribe(
                function (productAttributesSelected) {
                    self.isAttributesChanged = true;
                    self.productAttributesSelected(productAttributesSelected);
                    self.isAttributesChanged = false;
                }
            );

            attributes.productAttributes.subscribe(
                function (productAttributes) {
                    var allAttributes = productAttributes.map((object) => ({
                            ...object
                        })),
                        productAttributesSelected = productAttributes.filter(
                            function (productAttribute) {
                                return productAttribute.checked;
                            }
                        );

                    self.productAttributes(productAttributes);
                    self.allAttributes(allAttributes);
                    self.isAttributesChanged = true;
                    self.productAttributesSelected([]);

                    for (let key in productAttributesSelected) {
                        if (productAttributesSelected.hasOwnProperty(key)) {
                            self.productAttributesSelected.push(
                                productAttributesSelected[key].attribute_code
                            );
                        }
                    }
                    self.isAttributesChanged = false;
                }
            );

            self.productAttributesSelected.subscribe(
                function (productAttributesSelected) {
                    generateAttributes.productAttributesSelected([]);
                    for (let key in productAttributesSelected) {
                        if (productAttributesSelected.hasOwnProperty(key)) {
                            generateAttributes.productAttributesSelected.push(
                                productAttributesSelected[key]
                            );
                        }
                    }

                    if (self.canUpdate) {
                        self.updateSelect();
                    }

                    if (!self.isAttributesChanged) {
                        self.savePreferences();
                    }
                }
            );

            self.otherProductDetailsChecked.subscribe(
                function (otherProductDetailsChecked) {
                    generateAttributes.otherProductDetailsChecked(
                        otherProductDetailsChecked
                    );

                    if (!self.isAttributesChanged) {
                        self.savePreferences();
                    }
                }
            );

            self.otherProductDetails.subscribe(function (otherProductDetails) {
                generateAttributes.otherProductDetails(otherProductDetails);
            });

            this.updateSelect();
        },

        /** @inheritdoc */
        initObservable: function () {
            this._super().observe([
                'productAttributes',
                'allAttributes',
                'productId',
                'storeId',
                'productAttributesSelected',
                'otherProductDetails',
                'otherProductDetailsChecked',
                'selectAllValue',
                'productAttributesSelectedNotPremium'
            ]);

            return this;
        },

        /**
         * Preview image.
         *
         * @param {string} image
         * @returns {void}
         */
        preview: function (image) {
            var modalHtml = mageTemplate(
                thumbnailPreviewTemplate,
                {
                    src: image,
                    alt: '',
                    link: '',
                    linkText: ''
                    }
            ),
                previewPopup = $('<div/>').html(modalHtml);

            previewPopup.modal({
                title: '',
                innerScroll: true,
                modalClass: '_image-box',
                buttons: []
            }).trigger('openModal');
        },

        /**
         * Save thumbnail selected.
         *
         * @param {Object} data
         * @param {Event} event
         *
         * @returns {void}
         */
        saveThumbnailSelected: function (data, event) {
            $.ajax({
                url: self.saveSettingsUrl,
                type: 'POST',
                data: {
                    thumbnail: event.target.checked
                },
                dataType: 'json',
                showLoader: false,
                success: function (response) {
                    if (!response.success) {
                        console.log(response);
                    }
                }
            });
        },

        /**
         * Save product research data selected.
         *
         * @param {Object} data
         * @param {Event} event
         *
         * @returns {void}
         */
        saveProductResearchDataSelected: function (data, event) {
            $.ajax({
                url: self.saveSettingsUrl,
                type: 'POST',
                data: {
                    wtai_product_research_data: event.target.checked,
                    entity_type: '',
                },
                dataType: 'json',
                showLoader: false,
                success: function (response) {
                    if (!response.success) {
                        console.log(response);
                    }
                }
            });
        },

        /**
         * Save user preferences
         */
        savePreferences: function () {
            var productId = self.productId(),
                storeId = self.storeId(),
                productAttributesSelected = self.productAttributesSelected(),
                otherProductDetails = self.otherProductDetails(),
                otherProductDetailsChecked = self.otherProductDetailsChecked();
            
            $.ajax({
                url: self.saveUrl,
                type: 'POST',
                data: {
                    product_id: productId,
                    store_id: storeId,
                    product_attributes_selected: productAttributesSelected,
                    other_product_details: otherProductDetails,
                    other_product_details_checked: otherProductDetailsChecked
                },
                dataType: 'json',
                showLoader: false,
                success: function (response) {
                    if (!response.success) {
                        console.log(response);
                    }
                }
            });
        },

        /**
         * Get other product details length.
         */
        getOtherProductDetailsLength: function () {
            var otherProductDetailsLength = this.otherProductDetails()
                ? this.otherProductDetails().length : 0;

            return (
                otherProductDetailsLength +
                '/' +
                this.rules.maxOtherDetailsLength +
                ' ' +
                $t('Char')
            );
        },

        /**
         * Select all attributes
         */
        selectAllAttributes: function () {
            var productAttributesSelected = self.productAttributes(),
                attributeCodes = productAttributesSelected.map(function (attribute) {
                    return attribute.attribute_code;
                });

            this.canUpdate = false;
            if (this.selectAllValue()) {
                self.productAttributesSelected(attributeCodes);
            } else {
                self.productAttributesSelected([]);
            }
            this.canUpdate = true;

            $.ajax({
                url: self.saveSettingsUrl,
                type: 'POST',
                data: {
                    thumbnail: this.selectAllValue()
                },
                dataType: 'json',
                showLoader: false,
                success: function (response) {
                    if (!response.success) {
                        console.log(response);
                    }
                }
            });
        },

        /**
         * Update select all value
         */
        updateSelect: function () {
            const selectedAttributes = self.productAttributesSelected();
            const allAttributes = self.allAttributes();
            const allSelected = allAttributes.every(
                attr =>
                selectedAttributes.includes(attr.attribute_code)
            );
            this.selectAllValue(allSelected);
        },

        /**
         * Handle input custom audience.
         */
        handleInputOtherProductDetails: function () {
            clearTimeout(self.typingTimer);

            self.typingTimer = setTimeout(function () {
                if (!self.isAttributesChanged) {
                    self.savePreferences();
                }
            }, 2000);
        },
    });
});
