Vue.component('submit-button-conditional-logics', {
    template: '#tmpl-wpuf-submit-button-conditional-logic',

    props: {
        'current-settings': {
            type: Object,
            default: () => ({
                condition_status: 'no',
                cond_logic: 'any',
                conditions: [{
                    name: '',
                    operator: '=',
                    option: ''
                }]
            })
        },
        'label': {
            type: String,
            default: 'Conditional Logic on Submit Button'
        }
    },

    data: function() {
        return {
            // Internal reactive state for conditional logic settings
            condition_status: 'no',
            cond_logic: 'any',
            conditions: [],
            // Flag to track if component has been initialized
            isInitialized: false,
            rule_options: [
                {
                    label: 'All',
                    value: 'all',
                },
                {
                    label: 'Any',
                    value: 'any',
                }
            ],
            all_conditional_operators: {
                radio: [
                    {
                        label: 'is',
                        value: '=',
                    },
                    {
                        label: 'is not',
                        value: '!=',
                    },
                    {
                        label: 'any selection',
                        value: '!=empty',
                    },
                    {
                        label: 'no selection',
                        value: '==empty',
                    }
                ],
                text: [
                    {
                        label: 'is',
                        value: '=',
                    },
                    {
                        label: 'is not',
                        value: '!=',
                    },
                    {
                        label: 'contains',
                        value: '==contains',
                    },
                    {
                        label: 'has any value',
                        value: '!=empty',
                    },
                    {
                        label: 'has no value',
                        value: '==empty',
                    }
                ],
                number: [
                    {
                        label: 'is',
                        value: '=',
                    },
                    {
                        label: 'is not',
                        value: '!=',
                    },
                    {
                        label: 'contains',
                        value: '==contains',
                    },
                    {
                        label: 'has any value',
                        value: '!=empty',
                    },
                    {
                        label: 'has no value',
                        value: '==empty',
                    },
                    {
                        label: 'value is greater then',
                        value: 'greater',
                    },
                    {
                        label: 'value is less then',
                        value: 'less',
                    }
                ],
                dropdown: [
                    {
                        label: 'is',
                        value: '=',
                    },
                    {
                        label: 'is not',
                        value: '!=',
                    },
                    {
                        label: 'any selection',
                        value: '!=empty',
                    },
                    {
                        label: 'no selection',
                        value: '==empty',
                    }
                ],
                checkbox: [
                    {
                        label: 'is',
                        value: '=',
                    },
                    {
                        label: 'is not',
                        value: '!=',
                    },
                    {
                        label: 'any selection',
                        value: '!=empty',
                    },
                    {
                        label: 'no selection',
                        value: '==empty',
                    }
                ],
                others: [
                    {
                        label: 'has any value',
                        value: '!=empty',
                    },
                    {
                        label: 'has no value',
                        value: '==empty',
                    }
                ]
            }
        };
    },

    computed: {
        // Get form fields that support conditional logic
        conditional_fields: function () {
            var compatibleFields = [],
                allowedTypes = ['radio_field', 'checkbox_field', 'dropdown_field', 'text_field', 'textarea_field', 'email_address', 'numeric_text_field'];

            if (!this.$store || !this.$store.state || !this.$store.state.form_fields) {
                return [];
            }

            this.$store.state.form_fields.forEach(function(field) {
                if (allowedTypes.includes(field.template) &&
                    field.name &&
                    field.label) {
                    compatibleFields.push({
                        name: field.name,
                        label: field.label,
                        template: field.template,
                        options: field.options || {},
                        input_type: field.input_type || field.template
                    });
                }
            });

            return compatibleFields;
        }
    },

    watch: {
        // Watch for changes in current settings prop
        currentSettings: {
            handler: function(newSettings) {
                // Only initialize if component hasn't been initialized yet
                if (!this.isInitialized) {
                    this.initializeFromSettings(newSettings);
                }
            },
            deep: true,
            immediate: true
        },

        // Watch for changes in internal state and update settings
        condition_status: function() {
            this.update_settings();
        },

        cond_logic: function() {
            this.update_settings();
        },

        // Watch for changes in conditions array
        conditions: {
            handler: function(newConditions, oldConditions) {
                if (!oldConditions) return;
                
                for (var i = 0; i < newConditions.length; i++) {
                    var newCondition = newConditions[i];
                    var oldCondition = oldConditions[i];
                    
                    if (!oldCondition) continue;
                    
                    // Check if field name changed
                    if (newCondition.name !== oldCondition.name) {
                        this.on_change_cond_field(i);
                    }
                    
                    // Check if operator changed
                    if (newCondition.operator !== oldCondition.operator) {
                        this.on_change_cond_operator(i);
                    }
                    
                    // Check if option changed
                    if (newCondition.option !== oldCondition.option) {
                        this.on_change_cond_option();
                    }
                }
                
                // Update settings when conditions change
                this.update_settings();
            },
            deep: true
        }
    },

    methods: {
        // Initialize component data from current settings
        initializeFromSettings: function(settings) {
            if (!settings) {
                settings = {
                    condition_status: 'no',
                    cond_logic: 'any',
                    conditions: []
                };
            }

            // Set reactive data properties
            this.condition_status = settings.condition_status || 'no';
            this.cond_logic = settings.cond_logic || 'any';

            if (!settings.conditions || !Array.isArray(settings.conditions) || settings.conditions.length === 0) {
                this.conditions = [{
                    id: this.generateUniqueId(),
                    name: '',
                    operator: '=',
                    option: '',
                    input_type: ''
                }];
            } else {
                var self = this;
                this.conditions = settings.conditions.map(function(condition) {
                    return {
                        id: condition.id || self.generateUniqueId(),
                        name: condition.name || '',
                        operator: condition.operator || '=',
                        option: condition.option || '',
                        input_type: condition.input_type || ''
                    };
                });

                // Set input_type for existing conditions and trigger change handlers
                this.$nextTick(function() {
                    for (var i = 0; i < self.conditions.length; i++) {
                        var condition = self.conditions[i];
                        
                        // Set input_type for existing conditions that have a field selected
                        if (condition.name) {
                            var field = self.conditional_fields.find(f => f.name === condition.name);
                            
                            if (field) {
                                // Map field template to input_type for frontend conditional logic
                                var inputType = '';
                                switch (field.template) {
                                    case 'radio_field':
                                        inputType = 'radio';
                                        break;
                                    case 'checkbox_field':
                                        inputType = 'checkbox';
                                        break;
                                    case 'dropdown_field':
                                        inputType = 'select';
                                        break;
                                    case 'text_field':
                                        inputType = 'text';
                                        break;
                                    case 'textarea_field':
                                        inputType = 'textarea';
                                        break;
                                    case 'email_address':
                                        inputType = 'email';
                                        break;
                                    case 'numeric_text_field':
                                        inputType = 'numeric_text';
                                        break;
                                    default:
                                        inputType = field.template.replace('_field', '');
                                        break;
                                }
                                condition.input_type = inputType;
                            }
                        }
                        // Manually trigger operator change handler for existing conditions
                        // Skip update_settings to avoid multiple calls
                        self.on_change_cond_operator(i, true);
                    }
                    // Call update_settings once after all conditions are processed
                    self.update_settings();
                });
            }

            // Mark component as initialized
            this.isInitialized = true;
        },

        // Get conditional operators based on field type
        get_cond_operators: function(fieldName) {
            var field = this.conditional_fields.find(f => f.name === fieldName);
            if (!field) {
                return this.all_conditional_operators.text;
            }

            var fieldType = field.template.replace('_field', '');

            // Map field types to operator sets
            switch (fieldType) {
                case 'radio':
                case 'dropdown':
                case 'checkbox':
                    return this.all_conditional_operators[fieldType] || this.all_conditional_operators.radio;
                case 'text':
                case 'textarea':
                case 'email_address':
                    return this.all_conditional_operators.text;
                case 'numeric_text':
                    return this.all_conditional_operators.number;
                default:
                    return this.all_conditional_operators.others;
            }
        },

        // Get field options for dropdown conditions
        get_cond_options: function(fieldName) {
            var field = this.conditional_fields.find(f => f.name === fieldName);
            if (!field || !field.options) {
                return [];
            }

            var options = [];
            for (var key in field.options) {
                if (field.options.hasOwnProperty(key)) {
                    options.push({
                        value: key,
                        label: field.options[key]
                    });
                }
            }
            return options;
        },

        // Check if we should show text input or dropdown for condition value
        show_textfield: function(fieldName) {
            var field = this.conditional_fields.find(f => f.name === fieldName);
            if (!field) {
                return true;
            }

            var fieldType = field.template;
            return fieldType === 'text_field' || fieldType === 'textarea_field' || fieldType === 'email_address' || fieldType === 'numeric_text_field';
        },

        show_dropdown: function(fieldName) {
            return !this.show_textfield(fieldName);
        },

        // Check if condition value input should be disabled
        is_disabled: function(operator) {
            return operator === '!=empty' || operator === '==empty';
        },

        // Generate unique ID for conditions
        generateUniqueId: function() {
            return 'condition_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
        },

        // Add new condition
        add_condition: function() {
            this.conditions.push({
                id: this.generateUniqueId(),
                name: '',
                operator: '=',
                option: '',
                input_type: ''
            });
        },

        // Remove condition
        delete_condition: function(index) {
            if (this.conditions.length > 1) {
                this.conditions.splice(index, 1);
            }
        },

        // Handle field selection change
        on_change_cond_field: function(index) {
            // Reset operator and option when field changes
            var fieldName = this.conditions[index].name;
            var field = this.conditional_fields.find(f => f.name === fieldName);
            var operators = this.get_cond_operators(fieldName);

            this.conditions[index].operator = operators.length > 0 ? operators[0].value : '=';
            this.conditions[index].option = '';
            
            // Map field template to input_type for frontend conditional logic
            var inputType = '';
            if (field && field.template) {
                switch (field.template) {
                    case 'radio_field':
                        inputType = 'radio';
                        break;
                    case 'checkbox_field':
                        inputType = 'checkbox';
                        break;
                    case 'dropdown_field':
                        inputType = 'select';
                        break;
                    case 'text_field':
                        inputType = 'text';
                        break;
                    case 'textarea_field':
                        inputType = 'textarea';
                        break;
                    case 'email_address':
                        inputType = 'email';
                        break;
                    case 'numeric_text_field':
                        inputType = 'numeric_text';
                        break;
                    default:
                        inputType = field.template.replace('_field', '');
                        break;
                }
            }
            this.conditions[index].input_type = inputType;
            this.update_settings();
        },

        // Handle operator selection change
        on_change_cond_operator: function(index, skipUpdateSettings) {
            // Clear option value for operators that don't need a value
            var operator = this.conditions[index].operator;
            if (operator === '!=empty' || operator === '==empty') {
                this.conditions[index].option = '';
            }
            if (!skipUpdateSettings) {
                this.update_settings();
            }
        },

        // Handle option value change
        on_change_cond_option: function() {
            this.update_settings();
        },

        // Update settings and emit changes to store
        update_settings: function() {
            var settings = {
                condition_status: this.condition_status,
                cond_logic: this.cond_logic,
                conditions: this.conditions.map(function(condition) {
                    return {
                        name: condition.name,
                        operator: condition.operator,
                        option: condition.option,
                        input_type: condition.input_type
                    };
                })
            };

            // Update the store using Vue's reactivity system
            if (this.$store && this.$store.state && this.$store.state.settings) {
                this.$set(this.$store.state.settings, 'submit_button_cond', settings);
            }
        }
    },

    created: function() {
        // Initialize component data from current settings
        this.initializeFromSettings(this.currentSettings);
    }
});
