/**
 * @author 1902 Software
 * @copyright Copyright © 2023 1902 Software (https://1902software.com/magento/)
 * @package WriteTextAI_WriteTextAI
 */
define([
    'jquery',
    'ko',
    'uiComponent'
], function ($, ko, Component) {
    'use strict';

    return Component.extend({
        defaults: {
            isVisible: false,
            pendingCallback: null
        },

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

            $('#wtaiEmptyTemplateConfirm > *').applyBindings(this);
            this.bindEvents();
        },

        /** @inheritdoc */
        initObservable: function () {
            this._super()
                .observe([
                    'isVisible',
                    'pendingCallback'
                ]);

            return this;
        },

        /**
         * Bind click events for the confirmation buttons
         */
        bindEvents: function () {
            var self = this;

            // Handle "Go back" button click
            $(document).on('click', '.wtai-empty-template-confirm .action-back', function (e) {
                e.preventDefault();
                e.stopPropagation();
                self.hideConfirmation();
            });

            // Handle "Continue" button click
            $(document).on('click', '.wtai-empty-template-confirm .action-accept', function (e) {
                e.preventDefault();
                e.stopPropagation();
                self.continueWithoutTemplate();
            });

            // Handle overlay click to close (same as go back)
            $(document).on('click', '.wtai-empty-template-confirm .wtai-empty-template-confirm-overlay', function (e) {
                e.preventDefault();
                e.stopPropagation();
                self.hideConfirmation();
            });
        },

        /**
         * Check if a template is selected for specific field types that require templates
         * @returns {boolean}
         */
        hasTemplateSelected: function () {
            // Define the field types that require template validation
            var requiredTemplateFields = ['page_title', 'product_description', 'short_product_description'];
            
            // Check if any of the required fields are selected
            var selectedFields = this.getSelectedFields();
            var hasRequiredField = selectedFields.some(function (field) {
                return requiredTemplateFields.includes(field);
            });
            
            // If no required fields are selected, don't show template confirmation
            if (!hasRequiredField) {
                return true; // Return true to skip template validation
            }
            
            // Check for template selection for the required fields
            var hasTemplateForRequiredFields = false;
            var hasTemplateForAllFields = true;
            
            requiredTemplateFields.forEach(function (fieldType) {
                if (selectedFields.includes(fieldType)) {
                    if (actionType === 'generate') {
                        // Check if template is selected for this field type
                        var templateSelect = $('select[name="wtai_generate_template_' + fieldType + '"]');
                        if (templateSelect.length && templateSelect.val()) {
                            hasTemplateForRequiredFields = true;
                        } else {
                            hasTemplateForAllFields = false;
                        }
                    } else {
                        // Check if template is selected for this field type
                        var templateSelect = $('select[name="wtai_template_' + fieldType + '"]');
                        if (templateSelect.length && templateSelect.val()) {
                            hasTemplateForRequiredFields = true;
                        } else {
                            hasTemplateForAllFields = false;
                        }
                    }
                }
            });

            return hasTemplateForAllFields;
        },

        /**
         * Get selected fields from the form
         * @returns {Array}
         */
        getSelectedFields: function () {
            var selectedFields = [];
            
            // Get selected fields from bulk generate form
            var generateFieldsCheckboxes = $('#wtaiBulkGenerateForm input[name="fields[]"]:checked');
            generateFieldsCheckboxes.each(function () {
                selectedFields.push($(this).val());
            });
            
            // Get selected fields from full automation form
            var fullAutomationFieldsCheckboxes = $('#wtaiBulkFullAutomationForm input[name="fields[]"]:checked');
            fullAutomationFieldsCheckboxes.each(function () {
                selectedFields.push($(this).val());
            });
            
            return selectedFields;
        },

        /**
         * Show the empty template confirmation popup
         * @param {Function} callback - Callback to execute if user continues
         */
        showConfirmation: function (callback) {
            this.pendingCallback(callback);
            this.isVisible(true);
            $('.wtai-empty-template-confirm').show();
            
            // Switch to templates tab when popup is shown
            this.showTemplatesTab();
        },

        /**
         * Show the templates tab
         */
        showTemplatesTab: function () {
            // Find and click the templates tab
            var templatesTab = $('.wtai-bulk-generate-popup .item.title a[href="#wtai-templates"], .wtai-bulk-full-automation-popup .item.title a[href="#wtai-templates"]');
            if (templatesTab.length && !templatesTab.hasClass('switch')) {
                templatesTab.trigger('click');
            }
            
            // Alternative approach - look for tab by text content
            if (templatesTab.length === 0) {
                $('.wtai-bulk-generate-popup .item.title a, .wtai-bulk-full-automation-popup .item.title a').each(function () {
                    if ($(this).text().toLowerCase().includes('template')) {
                        $(this).trigger('click');
                        return false; // break the loop
                    }
                });
            }
        },

        /**
         * Hide the empty template confirmation popup
         */
        hideConfirmation: function () {
            this.isVisible(false);
            this.pendingCallback(null);
            $('.wtai-empty-template-confirm').hide();
        },

        /**
         * Continue without template selection
         */
        continueWithoutTemplate: function () {
            var callback = this.pendingCallback();
            this.hideConfirmation();
            
            if (typeof callback === 'function') {
                callback();
            }
        },

        /**
         * Validate template selection and show confirmation if needed
         * @param {Function} callback - Callback to execute if validation passes
         * @returns {boolean}
         */
        validateTemplateSelection: function (callback) {
            if (this.hasTemplateSelected()) {
                // Template is selected, proceed directly
                if (typeof callback === 'function') {
                    callback();
                }
                return true;
            } else {
                // No template selected, show confirmation
                this.showConfirmation(callback);
                return false;
            }
        }
    });
});