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

define([
    'jquery',
    'underscore',
    'ko',
    'Magento_Ui/js/form/element/abstract',
    'WriteTextAI_WriteTextAI/js/utils/edit/textfields',
    'WriteTextAI_WriteTextAI/js/utils/grid/filters',
    'WriteTextAI_WriteTextAI/js/model/grid/filter',
    'mage/translate',
    'jquery/ui',
    'accordion'
], function (
    $,
    _,
    ko,
    Abstract,
    textfieldsUtils,
    filtersUtils,
    filterModel,
    $t
) {
    'use strict';

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

    return Abstract.extend({
        defaults: {
            aiStatusCheckboxSelector:
                '.wtai-status-filter [name="ai_status"]',
            contentVisible: false,
            filterBy: ko.observable(''),
            keywordAnalysisSelected: ko.observableArray([]),
            fieldsSelected: ko.observableArray([]),
            fields: ko.observableArray([]),
            statuses: ko.observableArray([]),
            statusSelected: ko.observable(''),
            aiStatuses: ko.observableArray([]),
            aiStatusesSelected: ko.observableArray([]),
            noActivityDays: ko.observable(),
            noActivity: ko.observableArray([]),
            writetextaiStatus: ko.observable(),
            autoTextOptimizations: ko.observableArray([]),
            autoTextOptimizationsSelected: ko.observable(''),
            default: {
                ai_fields: [],
                status: 'all',
                ai_status: [],
                no_activity_days: 7,
                review_status: [],
                auto_text_optimizations: 'show_all',
                filter_by: 'text_status',
                keyword_analysis: [],
                templates_fields: 'show_all'
            },
            links: {
                value: '${ $.provider }:${ $.dataScope }'
            },
            reviewStatusSelected: ko.observableArray([]),
            tooltipText: {
                /* eslint-disable-next-line max-len */
                notGenerated: $t('You have not yet generated any text for these categories. Basically, these are the categories that are "untouched" by WriteText.ai.'),
                /* eslint-disable-next-line max-len */
                edited: $t('You have generated and edited at least one text type for these categories, but you have not yet marked any of them as "Reviewed".'),
                /* eslint-disable-next-line max-len */
                reviewed: $t('You have marked these categories as "Reviewed" using the checkbox in the individual category editing page.')
            },
            selectors: {
                tooltipSelector:
                    '.wtai-status-filter .admin__field-tooltip-action'
            },
            templatesFields: ko.observableArray([]),
            templatesFieldsSelected: ko.observable(''),
            templateSelected: ko.observable(''),
        },

        valueChange: false,
        aiStatusChange: false,
        reviewStatusChange: false,
        parameterProcessed: false,
        keywordAnalysisChange: false,

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

            this.parseOptions();
            this.setInitValue();
            this.initSpinner();
            this.initTooltip();

            this.value.subscribe(function (value) {
                if (this.parameterProcessed === false) {
                    filtersUtils.processCustomUrlFilters(value, this);
                    this.parameterProcessed = true;
                }
                this.setInitValue();
            }, this);

            this.filterBy.subscribe(function (filterBy) {
                var value = this.value();
                
                if (!this.valueChange) {
                    if (typeof value === 'undefined') {
                        value = { ...this.default };
                    }

                    value.filter_by = filterBy;
                    this.value(value);
                }
            }, this);

            this.fieldsSelected.subscribe(function (fields) {
                var value = this.value();

                if (!this.valueChange) {
                    if (typeof value === 'undefined') {
                        value = { ...this.default };
                    }

                    value.ai_fields = fields;
                    this.value(value);
                }
            }, this);

            this.statusSelected.subscribe(function (status) {
                var value = this.value();

                if (!this.valueChange) {
                    if (typeof value === 'undefined') {
                        value = { ...this.default };
                    }

                    value.status = status;
                    this.value(value);
                }

                if (!this.aiStatusChange) {
                    /**
                     * If status is not writetextai, uncheck all ai statuses
                     * else check all ai statuses
                     */
                    if (status !== this.writetextaiStatus()) {
                        this.aiStatusesSelected([]);
                    } else {
                        this.aiStatusesSelected(
                            this.aiStatuses.map((aiStatus) => aiStatus.value)
                        );
                    }
                }
                
                if (!this.reviewStatusChange) {
                    /**
                     * If status is not review status, uncheck all review statuses
                     * else check all review statuses
                     */
                    if (status !== 'review_status') {
                        this.reviewStatusSelected([]);
                    } else {
                        this.reviewStatusSelected([
                            'for_rewrite',
                            'fact_check'
                        ]);
                    }
                }
            }, this);

            this.reviewStatusSelected.subscribe(function (reviewStatus) {
                var value = this.value();

                if (!this.valueChange) {
                    this.reviewStatusChange = true;
                    if (reviewStatus.length >= 1) {
                        this.statusSelected('review_status');
                    } else {
                        if (this.statusSelected() === 'review_status') {
                            value.status = 'all';
                            this.statusSelected('all');
                        }
                    }
                    this.reviewStatusChange = false;

                    if (typeof value === 'undefined') {
                        value = { ...this.default };
                    }

                    value.review_status = reviewStatus;
                    this.value(value);
                }
            }, this);

            this.aiStatusesSelected.subscribe(function (aiStatuses) {
                var value = this.value();

                if (!this.valueChange) {
                    this.aiStatusChange = true;
                    if (aiStatuses.length >= 1) {
                        this.statusSelected(this.writetextaiStatus());
                    } else {
                        if (this.statusSelected() === this.writetextaiStatus()) {
                            value.status = 'all';
                            this.statusSelected('all');
                        }
                    }
                    this.aiStatusChange = false;

                    if (typeof value === 'undefined') {
                        value = { ...this.default };
                    }

                    value.ai_status = aiStatuses;
                    this.value(value);
                }
            }, this);

            this.noActivityDays.subscribe(function (noActivityDays) {
                var value = this.value();

                if (!this.valueChange) {
                    this.statusSelected(this.noActivity());

                    if (typeof value === 'undefined') {
                        value = { ...this.default };
                    }

                    value.no_activity_days = noActivityDays;
                    this.value(value);
                }
            }, this);

            this.autoTextOptimizationsSelected.subscribe(function (autoTextOptimizations) {
                var value = this.value();

                if (!this.valueChange) {
                    if (typeof value === 'undefined') {
                        value = { ...this.default };
                    }

                    value.auto_text_optimizations = autoTextOptimizations;
                    this.value(value);
                }

                if (!this.keywordAnalysisChange) {
                    if (autoTextOptimizations !== 'optimized') {
                        this.keywordAnalysisSelected([]);
                    } else {
                        this.keywordAnalysisSelected([
                            'for_generation',
                            'generated',
                            'published'
                        ]);
                    }
                }
            }, this);

            this.keywordAnalysisSelected.subscribe(function (keywordAnalysis) {
                var value = this.value();
                if (!this.valueChange) {
                    this.keywordAnalysisChange = true;
                    if (keywordAnalysis.length >= 1) {
                        this.autoTextOptimizationsSelected('optimized');
                    } else {
                        if (this.autoTextOptimizationsSelected() === 'optimized') {
                            value.auto_text_optimizations = 'show_all';
                            this.autoTextOptimizationsSelected('show_all');
                        }
                    }
                    this.keywordAnalysisChange = false;

                    if (typeof value === 'undefined') {
                        value = { ...this.default };
                    }

                    value.keyword_analysis = keywordAnalysis;
                    this.value(value);
                }
            }, this);

            this.templatesFieldsSelected.subscribe(function (templatesFields) {
                var value = this.value();

                if (!this.valueChange) {
                    if (typeof value === 'undefined') {
                        value = { ...this.default };
                    }
                    
                    value.templates_fields = templatesFields;
                    this.value(value);
                    
                    /* Reset all template dropdowns to "select template" when a new template field is selected */
                    this.resetTemplateDropdowns();
                }
            }, this);

            this.templateSelected.subscribe(function (templateSelected) {
                var value = this.value();

                if (!this.valueChange) {
                    if (typeof value === 'undefined') {
                        value = { ...this.default };
                    }
                    
                    value.template_selected = templateSelected;
                    this.value(value);
                }
            }, this);

            filterModel.isResetTemplatesToAll.subscribe(function (isResetTemplatesToAll) {
                if (isResetTemplatesToAll) {
                    this.templatesFieldsSelected('show_all');
                }
            }, this);

            filterModel.isResetTemplateSelected.subscribe(function (isResetTemplateSelected) {
                if (isResetTemplateSelected) {
                    this.resetTemplateDropdowns();
                    filterModel.isResetTemplateSelected(false);
                }
            }, this);

            return this;
        },

        /** @inheritdoc */
        initObservable: function () {
            this._super().observe([
                'contentVisible',
                'fieldsSelected',
                'fields',
                'statuses',
                'statusSelected',
                'aiStatuses',
                'aiStatusesSelected',
                'noActivityDays',
                'noActivity',
                'writetextaiStatus',
                'reviewStatusSelected',
                'autoTextOptimizations',
                'autoTextOptimizationsSelected',
                'filterBy',
                'keywordAnalysisSelected',
                'templatesFields',
                'templatesFieldsSelected',
                'templateSelected'
            ]);

            return this;
        },

        /**
         * Init tooltip
         */
        initTooltip: function () {
            $(this.selectors.tooltipSelector).dropdown({
                parent: '.admin__field-tooltip',
                autoclose: true
            });
        },

        /**
         * Init spinner
         */
        initSpinner: function () {
            setTimeout(
                function () {
                    $('.wtai-status-filter .wtai-input-number').spinner({
                        min: 1,
                        max: 365,
                        numberFormat: 'n',
                        spin: function (event, ui) {
                            this.noActivityDays(ui.value);
                        }.bind(this),
                        change: function (event) {
                            this.noActivityDays(event.target.value);
                        }.bind(this)
                    });
                }.bind(this),
                5000
            );
        },

        /**
         * Validate min and max value
         *
         * @param {Object} data
         * @param {Object} event
         *
         * @return {void}
         */
        validateMinMax: function (data, event) {
            var value = event.target.value;

            if (value < 1) {
                event.target.value = 1;
            } else if (value > 365) {
                event.target.value = 365;
            }
        },

        /**
         * Validate number.
         *
         * @param {Object} data
         * @param {Object} event
         *
         * @return {void}
         */
        ensureNumerical: function (data, event) {
            return textfieldsUtils.ensureNumerical(event.key);
        },
        
        /**
         * Set initial value
         */
        setInitValue: function () {
            var value = this.value();

            this.valueChange = true;

            if (typeof value === 'undefined') {
                value = { ...this.default };
            }

            if (typeof value.ai_fields !== 'undefined') {
                this.fieldsSelected(value.ai_fields);
            }

            if (typeof value.status !== 'undefined') {
                this.statusSelected(value.status);
            }

            if (typeof value.ai_status !== 'undefined') {
                this.aiStatusesSelected(value.ai_status);
            }

            if (typeof value.no_activity_days !== 'undefined') {
                this.noActivityDays(value.no_activity_days);
            }

            if (typeof value.review_status !== 'undefined') {
                this.reviewStatusSelected(value.review_status);
            }

            if (typeof value.auto_text_optimizations !== 'undefined') {
                this.autoTextOptimizationsSelected(value.auto_text_optimizations);
            }

            if (typeof value.filter_by !== 'undefined') {
                this.filterBy(value.filter_by);
            }

            if (typeof value.keyword_analysis !== 'undefined') {
                this.keywordAnalysisSelected(value.keyword_analysis);
            }

            if (typeof value.templates_fields !== 'undefined') {
                this.templatesFieldsSelected(value.templates_fields);
            }

            if (typeof value.template_selected !== 'undefined') {
                this.templateSelected(value.template_selected);
            }


            this.valueChange = false;
        },

        /**
         * On click outside
         *
         * @param {Array} textFields
         * @returns {void}
         */
        outerClick: function (textFields = []) {
            var noActivityDays = self.value() ? self.value().no_activity_days : self.default.no_activity_days,
                noActivitySelected = self.value() ? self.value().status === self.noActivity() : false,
                autoTextOptimizations = self.value() ? self.value().auto_text_optimizations : self.default.auto_text_optimizations;

            /** Validate no activity days */
            if (noActivitySelected && noActivityDays < 1) {
                self.noActivityDays(1);
            } else if (noActivitySelected && noActivityDays > 365) {
                self.noActivityDays(365);
            }

            /** Reset textfields selected if empty */
            if (typeof self.value() === 'undefined' ||
                typeof self.value().ai_fields === 'undefined' ||
                self.value().ai_fields.length <= 0
            ) {
                self.fieldsSelected([...textFields]);
            }

            self.contentVisible(false);
        },

        /**
         * Clear all
         */
        clear: function () {
            var defaults = {
                ai_fields: [],
                status: 'all',
                ai_status: [],
                no_activity_days: 7,
                auto_text_optimizations: 'show_all',
                filter_by: 'text_status',
                keyword_analysis: [],
                templates_fields: 'show_all'
            };

            this.valueChange = true;
            this.aiStatusChange = true;
            this.reviewStatusChange = true;

            this.value({...defaults});
            this.fieldsSelected([...defaults.ai_fields]);
            this.statusSelected(defaults.status);
            this.noActivityDays(defaults.no_activity_days);
            this.reviewStatusSelected([...defaults.review_status]);
            this.aiStatusesSelected([...defaults.ai_status]);
            this.autoTextOptimizationsSelected(defaults.auto_text_optimizations);
            this.keywordAnalysisSelected([]);
            this.templatesFieldsSelected(defaults.templates_fields);
            this.templateSelected('');

            this.aiStatusChange = false;
            this.valueChange = false;
            this.reviewStatusChange = false;

            return this;
        },

        /**
         * Parse options
         */
        parseOptions: function () {
            var options = this.options,
                defaults = {},
                value = '';

            this.default.ai_fields = options[0].map((field) => field.value);

            defaults = { ...this.default };
            value = this.value() === 'undefined' ? defaults : this.value();
            if (typeof value.ai_fields === 'undefined') {
                value.ai_fields = defaults.ai_fields;
            }
            this.value(value);

            this.fields(options[0]);
            this.statuses(options[1]);
            this.aiStatuses(options[2]);
            this.noActivity(options[3]['value']);
            this.writetextaiStatus(options[4]['value']);
            this.autoTextOptimizations(options[5]);
            this.templatesFields(options[6]);
        },

        /**
         * Toggle content visible
         */
        toggleContentVisible: function () {
            this.contentVisible(!this.contentVisible());
        },

        /**
         * Get parameter by name
         *
         * @param {String} name
         *
         * @returns {String}
         */
        getParameterValueByName: function (name) {
            var url = new URL(window.location.href),
                searchParams = new URLSearchParams(url.search),
                value = searchParams.get(name);

            return value ? value : '';
        },

        /** @inheritdoc */
        getPreview: function () {
            var preview = '';

            switch (this.filterBy()) {
                case 'text_status':
                    switch (this.statusSelected()) {
                        case 'not_generated':
                            preview = $t('Not generated');
                            break;
                        case 'writetextai':
                            var aiStatusLabels = {
                                Generated: $t('Generated'),
                                Edited: $t('Edited'),
                                Reviewed: $t('Reviewed'),
                                ForTransferring: $t('Queued for transfer'),
                                Transferred: $t('Transferred')
                            };
                            preview = this.value().ai_status?.map((status) => aiStatusLabels[status]).join(', ');
                            break;
                        case 'review_status':
                            var labels = {
                                for_rewrite: $t('For rewrite'),
                                fact_check: $t('For fact checking')
                            };
                            preview = this.value().review_status?.map((status) => labels[status]).join(', ');
                            break;
                        case 'no_activity':
                            preview = $t('Without activity for the last') + ' ' + this.value().no_activity_days + ' ' + $t('day/s');
                            break;
                    }
                    break;
                case 'keyword_status':
                    switch (this.autoTextOptimizationsSelected()) {
                        case 'optimized':
                            preview = $t('With keyword analysis');
                            break;
                        case 'not_optimized':
                            preview = $t('No keyword analysis');
                            break;
                    }
                    break;
                case 'templates':
                    switch (this.templatesFieldsSelected()) {
                        case 'show_all':
                            preview = $t('All');
                            break;
                        default:
                            preview = this.templatesFieldsSelected();
                            break;
                    }
                    break;
            }

            return preview;
        },

        /**
         * Check if template is selected
         *
         * @param {Object} parentFieldTemplateValue
         * @param {Object} template
         *
         * @returns {Boolean}
         */
        isTemplateSelected: function (parentFieldTemplateValue, template) {
            if (parentFieldTemplateValue === this.templatesFieldsSelected()) {
                return template.id === this.templateSelected();
            }
            if (template.id === '') {
                return true;
            }
            return false;
        },

        /**
         * Reset all template dropdowns to "Select template" (empty value)
         *
         * @returns {void}
         */
        resetTemplateDropdowns: function () {
            /* Reset template selected observable to empty */
            this.templateSelected('');
            
            /* Find and reset all template dropdown selects to empty value */
            setTimeout(function () {
                $('.wtai-select-template-filter').each(function () {
                    $(this).val('');
                });
            }, 100);
        },

        
    });
});
