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

define([
    'jquery',
    'ko',
    'uiComponent',
    'underscore',
    'WriteTextAI_WriteTextAI/js/model/edit/product',
    'WriteTextAI_WriteTextAI/js/model/edit/feedback',
    'WriteTextAI_WriteTextAI/js/utils/edit/textfields',
    'mage/dropdown'
], function (
    $,
    ko,
    Component,
    _,
    product,
    feedback,
    textfieldsUtils
) {
    'use strict';

    return Component.extend({
        defaults: {
            feedbackType: '',
            feedbackText: '',
            isLoading: false
        },

        isRatingChanged: false,
        sendingFeedback: null,

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

            this.feedbackType.subscribe(function (value) {
                if (this.isRatingChanged) {
                    this.sendFeedback(false);
                }
            }, this);

            feedback.feedbacks.subscribe(function (feedbacks) {
                this.resetFeedback();

                if (feedbacks[this.textType]) {
                    let feedbackText = feedbacks[this.textType].comment;
                    if (feedbackText) {
                        this.feedbackText(feedbackText);
                    }

                    let feedbackType = feedbacks[this.textType].rating;
                    if (feedbackType) {
                        this.feedbackType(feedbackType);
                    }
                }
            }, this);
        },

        /** @inheritdoc */
        initObservable: function () {
            this._super()
                .observe([
                    'feedbackType',
                    'feedbackText',
                    'isLoading'
                ]);

            this.count = ko.computed(function () {
                return textfieldsUtils.getCharCount(this.feedbackText(), this.textLimit);
            }, this);

            this.isLiked = ko.computed(function () {
                return this.feedbackType() === 'thumbs-up';
            }, this);

            this.isDisliked = ko.computed(function () {
                return this.feedbackType() === 'thumbs-down';
            }, this);

            return this;
        },

        /**
         * Reset feedback
         */
        resetFeedback: function () {
            this.feedbackText('');
            this.feedbackType('');
        },

        /**
         * Like
         */
        like: function () {
            if (this.feedbackType() === 'thumbs-up') {
                this.resetFeedback();
                this.deleteFeedback();
                $('.wtai-text-feedback-content.wtai-content-' + this.textType).removeClass('wtai-liked');
            } else {
                this.isRatingChanged = true;
                this.feedbackText('');
                this.feedbackType('thumbs-up');
                $('.wtai-text-feedback-content.wtai-content-' + this.textType).removeClass('wtai-disliked');
                $('.wtai-text-feedback-content.wtai-content-' + this.textType).addClass('wtai-liked');
                this.isRatingChanged = false;
            }
        },

        /**
         * Dislike
         */
        dislike: function () {
            if (this.feedbackType() === 'thumbs-down') {
                this.isRatingChanged = false;
                this.resetFeedback();
                this.deleteFeedback();
                $('.wtai-text-feedback-content.wtai-content-' + this.textType).removeClass('wtai-disliked');
            } else {
                this.isRatingChanged = true;
                this.feedbackText('');
                this.feedbackType('thumbs-down');
                $('.wtai-text-feedback-content.wtai-content-' + this.textType).removeClass('wtai-liked');
                $('.wtai-text-feedback-content.wtai-content-' + this.textType).addClass('wtai-disliked');
                this.isRatingChanged = false;
            }
        },

        /**
         * Send feedback
         *
         * @param {boolean} closePopup
         * @returns {void}
         */
        sendFeedback: function (closePopup = true) {
            if (this.sendingFeedback !== null) {
                this.sendingFeedback.abort();
            }
            
            if (closePopup) {
                this.isLoading(true);
            }

            this.sendingFeedback = $.ajax({
                url: this.feedbackUrl,
                type: 'POST',
                data: {
                    record_id: product.productId(),
                    store_id: product.storeId(),
                    field_type: this.textType,
                    rating: this.feedbackType(),
                    comment: this.feedbackText(),
                    entity_type: this.entityType
                },
                dataType: 'json',
                success: function (response) {
                    if (!response.success) {
                        console.log(response);
                    }
                }.bind(this),
                error: function (xhr, status, error) {
                    if (status !== 'abort') {
                        console.log(error);
                    }
                }
            }).always(function () {
                this.isLoading(false);
            }.bind(this));
        },

        /**
         * Delete feedback
         */
        deleteFeedback: function () {
            if (this.sendingFeedback !== null) {
                this.sendingFeedback.abort();
            }

            this.sendingFeedback = $.ajax({
                url: this.deleteFeedbackUrl,
                type: 'POST',
                data: {
                    record_id: product.productId(),
                    store_id: product.storeId(),
                    field_type: this.textType,
                    rating: this.feedbackType(),
                    comment: this.feedbackText(),
                    entity_type: this.entityType
                },
                dataType: 'json',
                success: function (response) {
                    if (!response.success) {
                        console.log(response);
                    }
                }.bind(this),
                error: function (xhr, status, error) {
                    if (status !== 'abort') {
                        console.log(error);
                    }
                }
            }).always(function () {
                this.isLoading(false);
            }.bind(this));
        }
    });
});
