Vue.component('integration-conditional-logic', {
    template: '#tmpl-wpuf-integration-conditional-logic',

    filters: {
        capitalize: function (value) {
            if (!value) {
                return '';
            }

            return value.charAt(0).toUpperCase() + value.slice(1);
        }
    },

    props: {
        'integration-name': {
            type: String,
            required: true
        },
        'settings-path': {
            type: String,
            required: true
        },
        'current-settings': {
            type: Object,
            default: () => ({
                condition_status: 'no',
                cond_logic: 'all',
                conditions: [{
                    name: '',
                    operator: '=',
                    option: ''
                }]
            })
        },
        'label': {
            type: String,
            default: 'Conditional Logic'
        }
    },

    data: function () {
        return {
            // Internal reactive state for conditional logic settings
            condition_status: 'no',
            cond_logic: 'all',
            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',
                    }
                ],
                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',
                    }
                ]
            }
        };
    },

    computed: {
        // Get form fields that support conditional logic
        conditional_fields: function () {
            var compatibleFields = [],
                allowedTypes = ['radio_field', 'checkbox_field', 'dropdown_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 || {}
                    });
                }
            });

            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() {
                this.update_settings();
            },
            deep: true
        }
    },

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

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

            if (!settings.conditions || !Array.isArray(settings.conditions) || settings.conditions.length === 0) {
                this.conditions = [{
                    id: this.generateUniqueId(),
                    name: '',
                    operator: '=',
                    option: ''
                }];
            } 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 || ''
                    };
                });

                // Validate all existing conditions
                this.$nextTick(function() {
                    self.validateAllConditions();
                });
            }

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

        // Validate all conditions to ensure they have valid operators and options
        validateAllConditions: function() {
            var self = this;
            var needsUpdate = false;

            this.conditions.forEach(function(condition, index) {
                if (condition.name) {
                    // Validate operator for the field type
                    var availableOperators = self.get_cond_operators(condition.name);
                    var operatorValid = availableOperators.some(function(op) {
                        return op.value === condition.operator;
                    });

                    if (!operatorValid && availableOperators.length > 0) {
                        condition.operator = availableOperators[0].value;
                        needsUpdate = true;
                    }

                    // Clear option if operator doesn't need a value
                    if (condition.operator === '!=empty' || condition.operator === '==empty') {
                        if (condition.option !== '') {
                            condition.option = '';
                            needsUpdate = true;
                        }
                    }
                }
            });

            // Force update if any validation changes were made
            if (needsUpdate) {
                this.$forceUpdate();
            }
        },

        // Get conditional operators based on field type
        get_cond_operators: function(fieldName) {
            if (!fieldName) {
                return this.all_conditional_operators.radio; // Default to radio operators
            }

            var field = this.conditional_fields.find(function(f) {
                return f.name === fieldName;
            });

            if (!field || !field.template) {
                return this.all_conditional_operators.radio; // Default to radio operators
            }

            // Extract field type from template (remove '_field' suffix)
            var fieldType = field.template.replace('_field', '');

            // Return operators for the field type, default to radio if not found
            return this.all_conditional_operators[fieldType] || this.all_conditional_operators.radio;
        },

        // Get field options for dropdown conditions
        get_cond_options: function(fieldName) {
            if (!fieldName) {
                return [];
            }

            var field = this.conditional_fields.find(function(f) {
                return f.name === fieldName;
            });

            if (!field || !field.options || typeof field.options !== 'object') {
                return [];
            }

            var options = [];

            // Handle both object and array format options
            if (Array.isArray(field.options)) {
                // Array format: [{label: 'Label', value: 'value'}, ...]
                field.options.forEach(function(option) {
                    if (option && typeof option === 'object' && option.label && option.value !== undefined) {
                        options.push({
                            value: option.value,
                            label: option.label
                        });
                    }
                });
            } else {
                // Object format: {value: 'label', ...} or {key: {label: 'Label', value: 'value'}}
                for (var key in field.options) {
                    if (field.options.hasOwnProperty(key)) {
                        var option = field.options[key];

                        if (typeof option === 'string') {
                            // Simple key-value format: {value: 'label'}
                            options.push({
                                value: key,
                                label: option
                            });
                        } else if (typeof option === 'object' && option.label && option.value !== undefined) {
                            // Complex object format: {key: {label: 'Label', value: 'value'}}
                            options.push({
                                value: option.value,
                                label: option.label
                            });
                        }
                    }
                }
            }

            return options;
        },

        // Check if we should show text input or dropdown for condition value
        show_textfield: function(fieldName) {
            // We only support checkbox, radio, and dropdown fields
            // All of these should show dropdown for their options
            return false;
        },

        show_dropdown: function(fieldName) {
            // We only support checkbox, radio, and dropdown fields
            // All of these should show dropdown for their options
            return true;
        },

        // 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: ''
            });
        },

        // 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) {
            var condition = this.conditions[index];
            var fieldName = condition.name;

            // Get available operators for the new field
            var availableOperators = this.get_cond_operators(fieldName);
            var currentOperator = condition.operator;

            // Check if current operator is valid for the new field
            var operatorValid = availableOperators.some(function(op) {
                return op.value === currentOperator;
            });

            // Reset operator to first available if current is invalid
            if (!operatorValid && availableOperators.length > 0) {
                condition.operator = availableOperators[0].value;
            }

            // Reset option value
            condition.option = '';

            // Force reactivity update for options dropdown
            this.$forceUpdate();

            // Validate the operator after field change
            this.on_change_cond_operator(index, true);
        },

        // Handle operator selection change
        on_change_cond_operator: function(index, skipUpdateSettings) {
            var condition = this.conditions[index];
            var operator = condition.operator;

            // Clear option value for operators that don't need a value
            if (operator === '!=empty' || operator === '==empty') {
                condition.option = '';
            }

            // Force update to ensure UI reflects the disabled state
            this.$forceUpdate();
        },

        // Handle option value change
        on_change_cond_option: function(index) {
            // Force update to ensure changes are reflected
            this.$forceUpdate();
        },

        // Update settings and emit changes
        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
                    };
                })
            };

            // Update the Vuex store directly using the settings path
            if (this.$store && this.$store.state && this.$store.state.settings) {
                // Create nested path in settings based on settingsPath
                var pathParts = this.settingsPath.split('.');
                var current = this.$store.state.settings;

                // Create nested objects if they don't exist
                for (var i = 0; i < pathParts.length - 1; i++) {
                    if (!current[pathParts[i]]) {
                        this.$set(current, pathParts[i], {});
                    }
                    current = current[pathParts[i]];
                }

                // Set the final value
                this.$set(current, pathParts[pathParts.length - 1], settings);
            }
        },

        // Reset component to allow re-initialization (useful when switching integrations)
        reset: function() {
            this.isInitialized = false;
            this.initializeFromSettings(this.currentSettings);
        }
    },

    created: function() {
        // The watcher with immediate: true will handle initialization
    }
});
