/**
 * Evolution API Settings Modal
 * Handles Evolution API configuration for WhatsApp instances
 */

let evolutionSettingsData = null;

/**
 * Open Evolution API Settings Modal
 */
async function openEvolutionSettingsModal() {
    try {
        // Load current Evolution API settings
        const response = await fetch('/api/superadmin/settings/evolution', {
            headers: { 'Authorization': `Bearer ${localStorage.getItem('superadmin_token')}` }
        });
        
        const data = await response.json();
        evolutionSettingsData = data.success ? data.data : {};
        
    } catch (error) {
        console.error('Error loading Evolution API settings:', error);
        evolutionSettingsData = {};
    }

    const modalHtml = `
        <div class="modal-overlay active" id="evolutionSettingsModal" onclick="closeEvolutionSettingsModal(event)">
            <div class="modal-dialog modal-lg" onclick="event.stopPropagation()">
                <div class="modal-content">
                    <div class="modal-header">
                        <h3>
                            <i class="fab fa-whatsapp"></i> 
                            <span data-i18n="evolution.title">Evolution API Configuration</span>
                        </h3>
                        <button class="modal-close" onclick="closeEvolutionSettingsModal()">&times;</button>
                    </div>
                    <div class="modal-body">
                        <!-- Info Banner -->
                        <div class="meta-info-banner">
                            <div class="meta-info-icon">
                                <i class="fas fa-info-circle"></i>
                            </div>
                            <div class="meta-info-content">
                                <h4 data-i18n="evolution.banner_title">Evolution API - WhatsApp Multi-Device</h4>
                                <p data-i18n="evolution.banner_description">Configure your Evolution API server to enable WhatsApp Web and Business API instances for your tenants.</p>
                            </div>
                        </div>

                        <form id="evolutionSettingsForm" onsubmit="saveEvolutionSettings(event)">
                            <!-- Enable/Disable Toggle -->
                            <div class="form-group">
                                <div class="meta-toggle-container">
                                    <div class="meta-toggle-info">
                                        <label class="meta-toggle-label" data-i18n="evolution.enable_label">Enable Evolution API</label>
                                        <small class="form-text" data-i18n="evolution.enable_description">Allow tenants to create WhatsApp instances via Evolution API</small>
                                    </div>
                                    <label class="toggle-switch">
                                        <input type="checkbox" id="evolutionEnabled" 
                                            ${evolutionSettingsData.evolution_enabled === '1' || evolutionSettingsData.evolution_enabled === 'true' || evolutionSettingsData.evolution_enabled === true ? 'checked' : ''}>
                                        <span class="toggle-slider"></span>
                                    </label>
                                </div>
                            </div>

                            <div class="meta-divider"></div>

                            <!-- Evolution API URL -->
                            <div class="form-group">
                                <label for="evolutionApiUrl">
                                    <span data-i18n="evolution.api_url">Evolution API URL</span>
                                    <span class="required-badge" data-i18n="evolution.required">Required</span>
                                </label>
                                <input type="url" id="evolutionApiUrl" class="form-control" 
                                    value="${evolutionSettingsData.evolution_api_url || ''}" 
                                    placeholder="https://evolution.yourdomain.com">
                                <small class="form-text">
                                    <i class="fas fa-question-circle"></i>
                                    <span data-i18n="evolution.api_url_help">The base URL of your Evolution API server (without trailing slash)</span>
                                </small>
                            </div>

                            <!-- Evolution API Key -->
                            <div class="form-group">
                                <label for="evolutionApiKey">
                                    <span data-i18n="evolution.api_key">Global API Key</span>
                                    <span class="required-badge" data-i18n="evolution.required">Required</span>
                                </label>
                                <div class="input-with-icon">
                                    <input type="password" id="evolutionApiKey" class="form-control" 
                                        value="${evolutionSettingsData.evolution_api_key || ''}" 
                                        placeholder="${evolutionSettingsData.evolution_api_key ? '********' : 'Enter your global API key'}">
                                    <button type="button" class="input-icon-btn" onclick="togglePasswordVisibility('evolutionApiKey')">
                                        <i class="fas fa-eye"></i>
                                    </button>
                                </div>
                                <small class="form-text">
                                    <i class="fas fa-shield-alt"></i>
                                    <span data-i18n="evolution.api_key_help">The global API key configured in your Evolution API server</span>
                                </small>
                            </div>

                            <!-- Webhook Base URL -->
                            <div class="form-group">
                                <label for="evolutionWebhookBaseUrl">
                                    <span data-i18n="evolution.webhook_base_url">Webhook Base URL</span>
                                    <span class="optional-badge" data-i18n="evolution.optional">Optional</span>
                                </label>
                                <div class="input-with-icon">
                                    <input type="url" id="evolutionWebhookBaseUrl" class="form-control" 
                                        value="${evolutionSettingsData.evolution_webhook_base_url || window.location.origin}" 
                                        placeholder="${window.location.origin}">
                                    <button type="button" class="input-icon-btn" onclick="copyWebhookBaseUrl()">
                                        <i class="fas fa-copy"></i>
                                    </button>
                                </div>
                                <small class="form-text">
                                    <i class="fas fa-question-circle"></i>
                                    <span data-i18n="evolution.webhook_base_url_help">The base URL where Evolution API will send webhooks (defaults to current domain)</span>
                                </small>
                            </div>

                            <!-- Webhook Path -->
                            <div class="form-group">
                                <label for="evolutionWebhookPath">
                                    <span data-i18n="evolution.webhook_path">Webhook Path</span>
                                </label>
                                <div class="input-with-icon">
                                    <input type="text" id="evolutionWebhookPath" class="form-control" 
                                        value="/api/webhooks/evolution" 
                                        readonly>
                                    <button type="button" class="input-icon-btn" onclick="copyFullWebhookUrl()">
                                        <i class="fas fa-copy"></i>
                                    </button>
                                </div>
                                <small class="form-text">
                                    <i class="fas fa-info-circle"></i>
                                    <span data-i18n="evolution.webhook_path_help">Full webhook URL: <code id="fullWebhookUrl">${evolutionSettingsData.evolution_webhook_base_url || window.location.origin}/api/webhooks/evolution/{tenantId}</code></span>
                                </small>
                            </div>

                            <div class="meta-divider"></div>

                            <!-- Setup Guide -->
                            <div class="meta-setup-guide">
                                <h4>
                                    <i class="fas fa-book"></i>
                                    <span data-i18n="evolution.setup_guide">Setup Guide</span>
                                </h4>
                                <ol class="meta-setup-steps">
                                    <li>
                                        <strong data-i18n="evolution.step1_title">Install Evolution API</strong>
                                        <p data-i18n="evolution.step1_description">Deploy Evolution API on your server using Docker or manual installation</p>
                                    </li>
                                    <li>
                                        <strong data-i18n="evolution.step2_title">Configure API Key</strong>
                                        <p data-i18n="evolution.step2_description">Set a strong global API key in your Evolution API configuration</p>
                                    </li>
                                    <li>
                                        <strong data-i18n="evolution.step3_title">Get API URL</strong>
                                        <p data-i18n="evolution.step3_description">Copy your Evolution API server URL (e.g., https://evolution.yourdomain.com)</p>
                                    </li>
                                    <li>
                                        <strong data-i18n="evolution.step4_title">Test Connection</strong>
                                        <p data-i18n="evolution.step4_description">Use the "Test Connection" button below to verify your configuration</p>
                                    </li>
                                    <li>
                                        <strong data-i18n="evolution.step5_title">Enable for Tenants</strong>
                                        <p data-i18n="evolution.step5_description">Once configured, tenants can create WhatsApp instances from their admin panel</p>
                                    </li>
                                </ol>
                                <div class="meta-setup-links">
                                    <a href="https://doc.evolution-api.com" target="_blank" class="btn btn-secondary btn-sm">
                                        <i class="fas fa-book"></i>
                                        <span data-i18n="evolution.view_documentation">View Documentation</span>
                                    </a>
                                    <a href="https://github.com/EvolutionAPI/evolution-api" target="_blank" class="btn btn-secondary btn-sm">
                                        <i class="fab fa-github"></i>
                                        <span data-i18n="evolution.github_repo">GitHub Repository</span>
                                    </a>
                                </div>
                            </div>

                            <!-- Connection Status -->
                            <div class="meta-connection-status" id="evolutionConnectionStatus" style="display: none;">
                                <div class="status-icon">
                                    <i class="fas fa-check-circle"></i>
                                </div>
                                <div class="status-content">
                                    <h5 data-i18n="evolution.connection_status">Connection Status</h5>
                                    <p id="evolutionConnectionMessage" data-i18n="evolution.not_tested">Not tested yet</p>
                                </div>
                            </div>
                            
                            <div class="form-actions mt-4">
                                <button type="button" class="btn btn-secondary" onclick="closeEvolutionSettingsModal()">
                                    <span data-i18n="evolution.cancel">Cancel</span>
                                </button>
                                <button type="button" class="btn btn-info" onclick="testEvolutionConnection()">
                                    <i class="fas fa-vial"></i>
                                    <span data-i18n="evolution.test_connection">Test Connection</span>
                                </button>
                                <button type="submit" class="btn btn-primary">
                                    <i class="fas fa-save"></i>
                                    <span data-i18n="evolution.save_configuration">Save Configuration</span>
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    `;

    document.body.insertAdjacentHTML('beforeend', modalHtml);
    
    // Update full webhook URL display
    updateFullWebhookUrl();
    
    // Apply translations if available
    if (typeof i18n !== 'undefined' && i18n.translatePage) {
        i18n.translatePage();
    }
}

/**
 * Close Evolution Settings Modal
 */
function closeEvolutionSettingsModal(event) {
    if (event && event.target !== event.currentTarget) return;
    
    const modal = document.getElementById('evolutionSettingsModal');
    if (modal) {
        modal.remove();
    }
}

/**
 * Update full webhook URL display
 */
function updateFullWebhookUrl() {
    const baseUrl = document.getElementById('evolutionWebhookBaseUrl')?.value || window.location.origin;
    const fullUrl = `${baseUrl}/api/webhooks/evolution/{tenantId}`;
    const fullWebhookUrlElement = document.getElementById('fullWebhookUrl');
    if (fullWebhookUrlElement) {
        fullWebhookUrlElement.textContent = fullUrl;
    }
}

/**
 * Copy webhook base URL to clipboard
 */
function copyWebhookBaseUrl() {
    const input = document.getElementById('evolutionWebhookBaseUrl');
    const button = input.nextElementSibling;
    const icon = button.querySelector('i');
    
    navigator.clipboard.writeText(input.value).then(() => {
        icon.classList.remove('fa-copy');
        icon.classList.add('fa-check');
        button.style.color = '#10b981';
        
        showNotification('Webhook base URL copied!', 'success');
        
        setTimeout(() => {
            icon.classList.remove('fa-check');
            icon.classList.add('fa-copy');
            button.style.color = '';
        }, 2000);
    }).catch(() => {
        input.select();
        document.execCommand('copy');
        showNotification('Webhook base URL copied!', 'success');
    });
}

/**
 * Copy full webhook URL to clipboard
 */
function copyFullWebhookUrl() {
    const baseUrl = document.getElementById('evolutionWebhookBaseUrl').value;
    const fullUrl = `${baseUrl}/api/webhooks/evolution/{tenantId}`;
    const button = document.getElementById('evolutionWebhookPath').nextElementSibling;
    const icon = button.querySelector('i');
    
    navigator.clipboard.writeText(fullUrl).then(() => {
        icon.classList.remove('fa-copy');
        icon.classList.add('fa-check');
        button.style.color = '#10b981';
        
        showNotification('Full webhook URL copied!', 'success');
        
        setTimeout(() => {
            icon.classList.remove('fa-check');
            icon.classList.add('fa-copy');
            button.style.color = '';
        }, 2000);
    }).catch(() => {
        showNotification('Full webhook URL copied!', 'success');
    });
}

/**
 * Test Evolution API Connection
 */
async function testEvolutionConnection() {
    const statusDiv = document.getElementById('evolutionConnectionStatus');
    const statusIcon = statusDiv.querySelector('.status-icon i');
    const statusMessage = document.getElementById('evolutionConnectionMessage');
    
    // Get current form values
    const apiUrl = document.getElementById('evolutionApiUrl').value.trim();
    const apiKey = document.getElementById('evolutionApiKey').value.trim();
    
    if (!apiUrl || !apiKey) {
        showNotification('Please fill in API URL and API Key before testing', 'error');
        return;
    }
    
    // Don't test if API key is masked
    if (apiKey === '********') {
        showNotification('Please enter the actual API Key (not the masked value)', 'error');
        return;
    }
    
    // Show status div
    statusDiv.style.display = 'flex';
    statusDiv.className = 'meta-connection-status testing';
    statusIcon.className = 'fas fa-spinner fa-spin';
    statusMessage.textContent = 'Testing connection to Evolution API...';
    
    try {
        const response = await fetch('/api/superadmin/settings/evolution/test', {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${localStorage.getItem('superadmin_token')}`,
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                evolution_api_url: apiUrl,
                evolution_api_key: apiKey
            })
        });
        
        const result = await response.json();
        
        if (result.success) {
            statusDiv.className = 'meta-connection-status success';
            statusIcon.className = 'fas fa-check-circle';
            statusMessage.innerHTML = `
                <strong>Connection Successful!</strong><br>
                Status: ${result.data.status || 'Online'}<br>
                ${result.data.instanceCount !== undefined ? `Instances: ${result.data.instanceCount}` : ''}
            `;
            showNotification('Evolution API connection successful!', 'success');
        } else {
            statusDiv.className = 'meta-connection-status error';
            statusIcon.className = 'fas fa-times-circle';
            statusMessage.innerHTML = `
                <strong>Connection Failed</strong><br>
                ${result.message || 'Unknown error'}
                ${result.error ? `<br><small>${result.error}</small>` : ''}
                ${result.details ? `<br><small>Code: ${result.details.code || result.details.status || 'N/A'}</small>` : ''}
            `;
            showNotification(result.message || 'Connection test failed', 'error');
        }
    } catch (error) {
        console.error('Error testing Evolution API connection:', error);
        statusDiv.className = 'meta-connection-status error';
        statusIcon.className = 'fas fa-times-circle';
        statusMessage.innerHTML = `
            <strong>Connection Failed</strong><br>
            Network error or server unreachable<br>
            <small>${error.message}</small>
        `;
        showNotification('Error testing connection - check console for details', 'error');
    }
}

/**
 * Save Evolution API Settings
 */
async function saveEvolutionSettings(event) {
    event.preventDefault();
    
    const submitBtn = event.target.querySelector('button[type="submit"]');
    const originalText = submitBtn.innerHTML;
    submitBtn.disabled = true;
    submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Saving...';
    
    try {
        const formData = {
            evolution_enabled: document.getElementById('evolutionEnabled').checked,
            evolution_api_url: document.getElementById('evolutionApiUrl').value.trim(),
            evolution_api_key: document.getElementById('evolutionApiKey').value.trim(),
            evolution_webhook_base_url: document.getElementById('evolutionWebhookBaseUrl').value.trim()
        };
        
        // Don't send API key if it's masked
        if (formData.evolution_api_key === '********') {
            delete formData.evolution_api_key;
        }
        
        const response = await fetch('/api/superadmin/settings/evolution', {
            method: 'PUT',
            headers: {
                'Authorization': `Bearer ${localStorage.getItem('superadmin_token')}`,
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(formData)
        });
        
        const result = await response.json();
        
        if (result.success) {
            showNotification('Evolution API settings saved successfully!', 'success');
            
            // Update cached data
            evolutionSettingsData = { ...evolutionSettingsData, ...formData };
            
            // Close modal after a short delay
            setTimeout(() => {
                closeEvolutionSettingsModal();
            }, 1000);
        } else {
            showNotification(result.message || 'Failed to save settings', 'error');
            submitBtn.disabled = false;
            submitBtn.innerHTML = originalText;
        }
    } catch (error) {
        console.error('Error saving Evolution API settings:', error);
        showNotification('Error saving settings', 'error');
        submitBtn.disabled = false;
        submitBtn.innerHTML = originalText;
    }
}

/**
 * Show notification
 */
function showNotification(message, type = 'info') {
    // Check if there's a global notification function
    if (typeof window.globalShowNotification === 'function') {
        window.globalShowNotification(message, type);
        return;
    }
    
    // Fallback notification
    const notification = document.createElement('div');
    notification.className = `notification notification-${type}`;
    notification.innerHTML = `
        <i class="fas fa-${type === 'success' ? 'check-circle' : type === 'error' ? 'exclamation-circle' : 'info-circle'}"></i>
        <span>${message}</span>
    `;
    notification.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        padding: 15px 20px;
        background: ${type === 'success' ? '#10b981' : type === 'error' ? '#ef4444' : '#3b82f6'};
        color: white;
        border-radius: 8px;
        box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        z-index: 10000;
        display: flex;
        align-items: center;
        gap: 10px;
        animation: slideIn 0.3s ease;
    `;
    
    document.body.appendChild(notification);
    
    setTimeout(() => {
        notification.style.animation = 'slideOut 0.3s ease';
        setTimeout(() => notification.remove(), 300);
    }, 3000);
}
