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

define([
    'jquery',
    'uiComponent',
    'underscore',
    'ko',
    'WriteTextAI_WriteTextAI/js/model/edit/keywords/keyword-analysis',
    'WriteTextAI_WriteTextAI/js/model/edit/keywords/keyword-pipelines',
    'WriteTextAI_WriteTextAI/js/model/edit',
    'WriteTextAI_WriteTextAI/js/categories/model/edit',
    'WriteTextAI_WriteTextAI/js/model/edit/keywords/error-messages',
    'mage/calendar'
], function (
    $,
    Component,
    _,
    ko,
    keywordAnalysis,
    keywordPipelines,
    editData,
    categoriesEditData
) {
    'use strict';

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

    return Component.extend({
        defaults: {
            storeId: 0,
            recordId: 0,
            historySelectedDatetime: '',
            selectors: {
                calendar: '.wtai-calendar.wtai-calendar-snapshot',
                timeiItem: '.wtai-snapshot-time'
            }
        },

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

            categoriesEditData.currentCategory.subscribe(function (category) {
                this.recordId(category.categoryId);
                this.storeId(category.storeId);
            }, this);

            editData.currentProduct.subscribe(function (product) {
                this.recordId(product.productId);
                this.storeId(product.storeId);
            }, this);

            keywordAnalysis.currentlySelectedSnapshot.subscribe(function (snapshot) {
                let datePrepare = new Date(snapshot.date);
                /** TODO: Make language dynamic when enabling translations */
                let convertedDate = new Intl.DateTimeFormat('en-US', {
                    year: 'numeric',
                    month: 'long',
                    day: 'numeric',
                    hour: '2-digit',
                    minute: '2-digit',
                    hour12: false,
                    timeZone: self.timezone
                }).format(datePrepare);
                convertedDate = convertedDate.replace(' at ', ' ').trim();
                this.historySelectedDatetime(convertedDate);
            }, this);

            self = this;
        },

        /** @inheritdoc */
        initObservable: function () {
            this._super().observe([
                'storeId',
                'recordId',
                'historySelectedDatetime'
            ]);

            this.rankingHistory = ko.computed(function () {
                let snapshots = keywordAnalysis.snapshotData();
                if (!snapshots || Object.keys(snapshots).length === 0) {
                    return {};
                }

                snapshots.sort((a, b) => new Date(a.date) - new Date(b.date));

                let reduced = snapshots.reduce((acc, item) => {
                    let dateObj = new Date(item.date);
                    let formattedDate = dateObj.toISOString().split('T')[0];
                    let formattedTime = new Intl.DateTimeFormat('en-US', {
                        hour: '2-digit',
                        minute: '2-digit',
                        hour12: false,
                        timeZone: self.timezone
                    }).format(dateObj);
                
                if (!acc[formattedDate]) {
                    acc[formattedDate] = [];
                }
                
                    acc[formattedDate].push({
                        id: item.id,
                        time: formattedTime
                    });
                
                    return acc;
                }, {});
                return reduced;
            }, this);

            this.rankingHistoryDates = ko.computed(function () {
                let datekeys = Object.keys(this.rankingHistory());
                return datekeys;
            }, this);

            return this;
        },

        /**
         * Bind date filter calendar.
         */
        initCalendar: function () {
            var self = this;

            $(this.selectors.calendar).calendar({
                dateFormat: 'yy-mm-dd',
                changeMonth: true,
                changeYear: true,
                buttonText: "",
                showButtonPanel: false,
                beforeShow: function (input, inst) {
                    var rect = input.getBoundingClientRect();

                    setTimeout(function () {
                        var scrollTop = $("body").scrollTop();
                        inst.dpDiv.css({
                            top: rect.top + input.offsetHeight + scrollTop,
                            left: rect.left - ((inst.dpDiv.outerWidth() - input.offsetWidth))
                        });
                    }, 0);
                },
                beforeShowDay: function (date) {
                    var history = self.rankingHistory() || [];

                    let dateClass = 'wtai-has-ranking-history wtai-ranking-tooltip',
                        addClass = 'wtai-' + date.getFullYear() + '-' + String(date.getMonth() + 1).padStart(2, '0') + '-' + String(date.getDate()).padStart(2, '0'),
                        allClasses = dateClass + ' ' + addClass;
                        
                    let year = date.getFullYear(),
                        month = String(date.getMonth() + 1).padStart(2, '0'),
                        day = String(date.getDate()).padStart(2, '0'),
                        localDate = `${year}-${month}-${day}`;

                    if (history.hasOwnProperty(localDate)) {
                        if (history[localDate].length >= 1) {
                            return [true, allClasses];
                        } else {
                            return [true, 'wtai-has-ranking-history'];
                        }
                    }

                    return [false, ''];
                },
                onClose: function (dateText, inst) {
                    inst.inline = false;
                },
                onSelect: function (dateText, inst) {
                    var history = self.rankingHistory() || [];

                    if (history[dateText] === undefined) {
                        return;
                    }

                    if (history[dateText].length >= 1) {
                        return;
                    }

                    let snapshot = history[dateText][0] || null;
                    if (snapshot) {
                        self.viewHistory(snapshot.id);
                    }
                },
                onChangeMonthYear: function (year, month, inst) {
                    /** Add a delay as the onChangeMonthYear is trigger before the render */
                    setTimeout(function () {
                        self.processSnapshotTime(inst);
                    }, 100);
                }
            });

            $('.wtai-keyword-ranking-history .ui-datepicker-trigger').on('click', function () {
                self.processSnapshotTime();
            });
        },

        /**
         * Process snapshot time
         *
         * @param {object} inst
         * @return {void}
         */
        processSnapshotTime: function (inst = null) {
            var selector = '#ui-datepicker-div';
            if (inst) {
                selector = inst.dpDiv;
            }
            $(selector).find('td.wtai-has-ranking-history.wtai-ranking-tooltip').each(function () {
                const year = $(this).data('year');
                const month = $(this).data('month') + 1;
                const day = String($(this).find('a.ui-state-default').text()).padStart(2, '0');
                const dateStr = `${year}-${String(month).padStart(2, '0')}-${day}`;
                var rankingHistory = self.rankingHistory();
                var snapshotTime = rankingHistory[dateStr] || [];
                const date = new Date(dateStr);
                const formattedDate = date.toLocaleDateString('en-US', {
                    year: 'numeric',
                    month: 'long',
                    day: 'numeric'
                });
                if (snapshotTime.length >= 1) {
                    $(this).append('<div class="tooltip-content"></div>');
                    $(this).find('.tooltip-content').append(`<div class="wtai-date">${formattedDate}</div>`);
                    $(this).find('.tooltip-content').append('<ul class="wtai-group-time wtai-2024-11-21"></ul>');

                    var $this = $(this);

                    snapshotTime.map(function (snapshot) {
                        var snapshotId = snapshot.id;
                        let timeElem = $(`<li class="wtai-sample-time">${snapshot.time}</li>`);

                        timeElem.on('click', function () {
                            self.viewHistory(snapshotId);
                        });

                        $this.find('.wtai-group-time').append(timeElem);
                    });
                }
            });
        },

        /**
         * View History
         *
         * @param {*} snapshotId
         */
        viewHistory: function (snapshotId) {
            self.getSnapshotRequest(snapshotId);
        },

        /**
         * Format date
         *
         * @param {string} date
         */
        formatDate: function (date) {
            return new Date(date).toISOString().split('T')[0];
        },

        /**
         * Get tooltip class
         *
         * @param {string} date
         */
        getTooltipClass: function (date) {
            date = self.formatDate(date);
            return 'wtai-' + date;
        },

        /**
         * Get snapshot request
         *
         * @param {string} snapshotId
         */
        getSnapshotRequest: function (snapshotId) {
            $.ajax({
                url: self.getSnapshotUrl,
                type: 'POST',
                data: {
                    store_id : self.storeId(),
                    record_id: self.recordId(),
                    entity_type: self.entityType,
                    snapshot_id: snapshotId
                },
                dataType: 'json',
                showLoader: true,
                success: function (response) {
                    if (response.success === true) {
                        var currentOptmizationData = keywordAnalysis.optimizationData();
                        
                        if (keywordAnalysis.historyMode() === false) {
                            keywordAnalysis.storeCurrentOptimizationData(currentOptmizationData);
                        }
                        var snapshotResponse = response.api_response.data;
                        snapshotResponse.status = 'Completed';
                        keywordAnalysis.optimizationData({});
                        keywordAnalysis.optimizationData(response.api_response.data);
                        keywordAnalysis.currentlySelectedSnapshot(response.api_response.data);
                        keywordAnalysis.historyMode(true);
                        keywordPipelines.forceResetEditPipeline(false); /** set to false first to trigger change*/
                        keywordPipelines.forceResetEditPipeline(true);
                        keywordPipelines.editKeywordRankingVisible(false);
                        keywordPipelines.editKeywordRankingVisible.valueHasMutated();
                    } else {
                        if (typeof response.error !== 'undefined') {
                            errorMessagesModel.messages.push(response.error);
                        }
                    }
                }
            });
        }
    });
});
