// Odoo Configuration Page Logic
class OdooConfigManager {
    constructor() {
        this.apiUrl = 'http://127.0.0.1:8000';
        this.init();
    }

    async init() {
        this.bindEvents();
        await this.loadCurrentConfig();
    }

    bindEvents() {
        document.getElementById('saveBtn').addEventListener('click', () => this.saveAndTest());
        document.getElementById('testOnlyBtn').addEventListener('click', () => this.testWithoutSaving());
        
        // Clear messages when form changes
        const form = document.getElementById('configForm');
        form.addEventListener('input', () => {
            this.clearStatusMessage();
        });
    }

    async loadCurrentConfig() {
        try {
            const response = await fetch(`${this.apiUrl}/odoo/config`);
            if (response.ok) {
                const config = await response.json();
                this.populateForm(config);
                this.showStatusMessage('Current configuration loaded', 'info');
            }
        } catch (error) {
            console.log('No existing config found, using defaults');
        }
    }

    populateForm(config) {
        const fields = ['url', 'database', 'username', 'tagName'];
        fields.forEach(field => {
            const element = document.getElementById(field);
            if (element && config[field]) {
                element.value = config[field];
            }
        });

        // Handle checkbox
        const enableSync = document.getElementById('enableSync');
        if (config.enable_sync !== undefined) {
            enableSync.checked = config.enable_sync;
        }

        // Handle password field - show placeholder if password exists
        const passwordField = document.getElementById('password');
        if (config.has_password) {
            passwordField.placeholder = 'Password saved (leave blank to keep current)';
        } else {
            passwordField.placeholder = 'password or API key';
        }
        
        this.hasExistingPassword = config.has_password || false;
    }

    getFormData() {
        const form = document.getElementById('configForm');
        const formData = new FormData(form);
        const password = formData.get('password');
        
        const config = {
            url: formData.get('url'),
            database: formData.get('database'),
            username: formData.get('username'),
            enable_sync: document.getElementById('enableSync').checked,
            tag_name: formData.get('tagName') || 'synced'
        };
        
        // Only include password if it's provided or if there's no existing password
        if (password || !this.hasExistingPassword) {
            config.password = password;
        }
        
        return config;
    }

    async saveAndTest() {
        const config = this.getFormData();
        
        // Basic validation
        if (!config.url || !config.database || !config.username || !config.password) {
            this.showStatusMessage('Please fill in all required fields', 'error');
            return;
        }

        try {
            this.showLoading(false);
            const saveBtn = document.getElementById('saveBtn');
            saveBtn.textContent = 'Saving...';
            saveBtn.disabled = true;

            // First save the configuration
            const response = await fetch(`${this.apiUrl}/odoo/config`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(config)
            });

            const result = await response.json();
            
            if (response.ok && result.success) {
                this.showStatusMessage('Configuration saved! Testing connection...', 'info');
                // Now test the saved configuration
                await this.testConnection();
            } else {
                this.showStatusMessage(`Save failed: ${result.message}`, 'error');
            }
        } catch (error) {
            this.showStatusMessage(`Network error: ${error.message}`, 'error');
        } finally {
            const saveBtn = document.getElementById('saveBtn');
            saveBtn.textContent = 'Save & Test';
            saveBtn.disabled = false;
            this.hideLoading();
        }
    }

    async testWithoutSaving() {
        const config = this.getFormData();
        
        // Basic validation
        if (!config.url || !config.database || !config.username || !config.password) {
            this.showStatusMessage('Please fill in all required fields', 'error');
            return;
        }

        try {
            this.showLoading(true);
            const testBtn = document.getElementById('testOnlyBtn');
            testBtn.textContent = 'Testing...';
            testBtn.disabled = true;

            // First temporarily save configuration (server will test using this)
            const saveResponse = await fetch(`${this.apiUrl}/odoo/config`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(config)
            });

            if (!saveResponse.ok) {
                this.showStatusMessage('Failed to prepare test configuration', 'error');
                return;
            }

            // Now test the connection
            const response = await fetch(`${this.apiUrl}/odoo/test`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                }
            });

            const result = await response.json();
            
            if (result.success) {
                this.showStatusMessage(`✅ ${result.message} (configuration not permanently saved)`, 'success');
            } else {
                this.showStatusMessage(`❌ ${result.message}`, 'error');
            }
        } catch (error) {
            this.showStatusMessage(`❌ Network error: ${error.message}`, 'error');
        } finally {
            const testBtn = document.getElementById('testOnlyBtn');
            testBtn.textContent = 'Test Without Saving';
            testBtn.disabled = false;
            this.hideLoading();
        }
    }

    async testConnection() {
        try {
            const response = await fetch(`${this.apiUrl}/odoo/test`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                }
            });

            const result = await response.json();
            
            if (result.success) {
                this.showStatusMessage(`✅ ${result.message}`, 'success');
            } else {
                this.showStatusMessage(`❌ ${result.message}`, 'error');
            }
        } catch (error) {
            this.showStatusMessage(`❌ Network error: ${error.message}`, 'error');
        }
    }

    showStatusMessage(message, type) {
        const statusDiv = document.getElementById('statusMessage');
        statusDiv.textContent = message;
        statusDiv.className = `status-message status-${type}`;
        statusDiv.style.display = 'block';
        
        // Auto-hide success messages after 5 seconds
        if (type === 'success') {
            setTimeout(() => {
                statusDiv.style.display = 'none';
            }, 5000);
        }
    }

    clearStatusMessage() {
        const statusDiv = document.getElementById('statusMessage');
        statusDiv.style.display = 'none';
    }

    showLoading(show) {
        const loading = document.getElementById('loading');
        loading.style.display = show ? 'block' : 'none';
    }

    hideLoading() {
        this.showLoading(false);
    }
}

// Initialize when page loads
document.addEventListener('DOMContentLoaded', () => {
    new OdooConfigManager();
});

// Handle navigation back to main popup
window.addEventListener('beforeunload', () => {
    // Any cleanup if needed
});