{% extends "layout.html.twig" %}

{% block title %}Email System Management - LocalLendables Admin{% endblock %}

{% block content %}
<div class="container mt-4">
    <div class="row">
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h2>📧 Email Notification System</h2>
                <span class="badge bg-success">Admin Dashboard</span>
            </div>
            
            <!-- Status Overview Card -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="mb-0">System Status</h5>
                </div>
                <div class="card-body">
                    <div class="row" id="statusOverview">
                        <div class="col-md-3">
                            <div class="text-center">
                                <div class="h4 mb-1" id="schedulerStatus">
                                    <span class="spinner-border spinner-border-sm"></span>
                                </div>
                                <small class="text-muted">Scheduler</small>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="text-center">
                                <div class="h4 mb-1" id="apiKeyStatus">
                                    <span class="spinner-border spinner-border-sm"></span>
                                </div>
                                <small class="text-muted">SendGrid API</small>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="text-center">
                                <div class="h4 mb-1" id="temporaryEmail">
                                    <span class="spinner-border spinner-border-sm"></span>
                                </div>
                                <small class="text-muted">Temporary Routing</small>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="text-center">
                                <div class="h4 mb-1" id="todayDigests">
                                    <span class="spinner-border spinner-border-sm"></span>
                                </div>
                                <small class="text-muted">Today's Digests</small>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Quick Actions -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="mb-0">Quick Actions</h5>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-4">
                            <button type="button" class="btn btn-primary w-100 mb-2" onclick="testEmailConnection()">
                                <i class="fa fa-paper-plane"></i> Test Email Connection
                            </button>
                        </div>
                        <div class="col-md-4">
                            <button type="button" class="btn btn-info w-100 mb-2" onclick="refreshStatus()">
                                <i class="fa fa-refresh"></i> Refresh Status
                            </button>
                        </div>
                        <div class="col-md-4">
                            <button type="button" class="btn btn-warning w-100 mb-2" onclick="viewLogs()">
                                <i class="fa fa-list"></i> View Recent Logs
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Settings Configuration -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="mb-0">Email Settings</h5>
                </div>
                <div class="card-body" id="settingsForm">
                    <div class="text-center">
                        <div class="spinner-border" role="status">
                            <span class="visually-hidden">Loading settings...</span>
                        </div>
                        <p class="mt-2">Loading current settings...</p>
                    </div>
                </div>
            </div>

            <!-- Recent Logs -->
            <div class="card" id="logsCard" style="display: none;">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">Recent Email Logs</h5>
                    <button type="button" class="btn btn-sm btn-outline-secondary" onclick="hideLogs()">Hide</button>
                </div>
                <div class="card-body">
                    <div id="logsList">
                        <!-- Logs will be loaded here -->
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Toast notifications container -->
<div class="position-fixed bottom-0 end-0 p-3" style="z-index: 11">
    <div id="emailToast" class="toast align-items-center border-0" role="alert" aria-live="assertive" aria-atomic="true">
        <div class="d-flex">
            <div class="toast-body" id="toastMessage">
                <!-- Toast message content -->
            </div>
            <button type="button" class="btn-close me-2 m-auto" data-bs-dismiss="toast"></button>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Load initial status and settings
    refreshStatus();
    loadSettings();
});

async function refreshStatus() {
    try {
        const response = await fetch('/api/email/status');
        if (!response.ok) {
            throw new Error(`HTTP ${response.status}: ${response.statusText}`);
        }
        const data = await response.json();
        
        updateStatusDisplay(data);
        showToast('Status refreshed successfully', 'success');
    } catch (error) {
        console.error('Error fetching status:', error);
        updateStatusDisplay(null, error.message);
        showToast('Error refreshing status: ' + error.message, 'error');
    }
}

function updateStatusDisplay(data, errorMessage = null) {
    if (errorMessage) {
        document.getElementById('schedulerStatus').innerHTML = '<span class="text-danger">Error</span>';
        document.getElementById('apiKeyStatus').innerHTML = '<span class="text-danger">Error</span>';
        document.getElementById('temporaryEmail').innerHTML = '<span class="text-danger">Error</span>';
        document.getElementById('todayDigests').innerHTML = '<span class="text-danger">Error</span>';
        return;
    }
    
    // Update status indicators
    document.getElementById('schedulerStatus').innerHTML = data.schedulerRunning 
        ? '<span class="text-success">Running</span>' 
        : '<span class="text-danger">Stopped</span>';
    
    document.getElementById('apiKeyStatus').innerHTML = data.hasApiKey 
        ? '<span class="text-success">Connected</span>' 
        : '<span class="text-warning">Missing</span>';
    
    document.getElementById('temporaryEmail').innerHTML = data.temporaryEmail 
        ? `<small class="text-info">${data.temporaryEmail}</small>`
        : '<span class="text-muted">Not Set</span>';
    
    document.getElementById('todayDigests').innerHTML = data.todayStats 
        ? `<span class="text-primary">${data.todayStats.sent || 0}</span>`
        : '<span class="text-muted">0</span>';
}

async function loadSettings() {
    try {
        const response = await fetch('/api/email/settings');
        if (!response.ok) {
            throw new Error(`HTTP ${response.status}: ${response.statusText}`);
        }
        const settings = await response.json();
        
        displaySettingsForm(settings);
    } catch (error) {
        console.error('Error fetching settings:', error);
        document.getElementById('settingsForm').innerHTML = `
            <div class="alert alert-danger">
                <strong>Error loading settings:</strong> ${error.message}
                <br><small>Make sure you're logged in as an admin user.</small>
            </div>
        `;
    }
}

function displaySettingsForm(settings) {
    document.getElementById('settingsForm').innerHTML = `
        <form onsubmit="saveSettings(event)">
            <div class="row">
                <div class="col-md-6">
                    <div class="form-check form-switch mb-3">
                        <input class="form-check-input" type="checkbox" id="isEnabled" 
                               ${settings.is_enabled ? 'checked' : ''}>
                        <label class="form-check-label" for="isEnabled">
                            <strong>Enable Email Notifications</strong>
                        </label>
                    </div>
                    
                    <div class="form-check form-switch mb-3">
                        <input class="form-check-input" type="checkbox" id="temporaryMode" 
                               ${settings.temporary_mode ? 'checked' : ''}>
                        <label class="form-check-label" for="temporaryMode">
                            <strong>Temporary Mode</strong> (route all emails to single address)
                        </label>
                    </div>
                </div>
                
                <div class="col-md-6">
                    <div class="mb-3">
                        <label for="temporaryEmail" class="form-label">Temporary Email Address</label>
                        <input type="email" class="form-control" id="temporaryEmailInput" 
                               value="${settings.temporary_email || 'manager@tatacommons.com'}"
                               placeholder="manager@tatacommons.com">
                        <div class="form-text">All emails will be sent here during development</div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="scheduleTime" class="form-label">Daily Digest Schedule</label>
                        <input type="time" class="form-control" id="scheduleTime" 
                               value="${settings.daily_schedule_time || '09:00'}">
                        <div class="form-text">Time to send daily digest emails (UTC)</div>
                    </div>
                </div>
            </div>
            
            <div class="d-flex justify-content-end">
                <button type="submit" class="btn btn-success">
                    <i class="fa fa-save"></i> Save Settings
                </button>
            </div>
        </form>
    `;
}

async function saveSettings(event) {
    event.preventDefault();
    
    const settings = {
        is_enabled: document.getElementById('isEnabled').checked,
        temporary_mode: document.getElementById('temporaryMode').checked,
        temporary_email: document.getElementById('temporaryEmailInput').value,
        daily_schedule_time: document.getElementById('scheduleTime').value
    };
    
    try {
        const response = await fetch('/api/email/settings', {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(settings)
        });
        
        if (!response.ok) {
            throw new Error(`HTTP ${response.status}: ${response.statusText}`);
        }
        
        const result = await response.json();
        showToast('Settings saved successfully!', 'success');
        refreshStatus(); // Refresh status after saving
    } catch (error) {
        console.error('Error saving settings:', error);
        showToast('Error saving settings: ' + error.message, 'error');
    }
}

async function testEmailConnection() {
    try {
        const response = await fetch('/api/email/test', {
            method: 'POST'
        });
        
        if (!response.ok) {
            throw new Error(`HTTP ${response.status}: ${response.statusText}`);
        }
        
        const result = await response.json();
        
        if (result.success) {
            showToast('Email test successful! Check manager@tatacommons.com', 'success');
        } else {
            showToast('Email test failed: ' + result.message, 'error');
        }
    } catch (error) {
        console.error('Error testing email:', error);
        showToast('Error testing email: ' + error.message, 'error');
    }
}

async function viewLogs() {
    try {
        const response = await fetch('/api/email/logs');
        if (!response.ok) {
            throw new Error(`HTTP ${response.status}: ${response.statusText}`);
        }
        
        const logs = await response.json();
        displayLogs(logs);
        document.getElementById('logsCard').style.display = 'block';
        document.getElementById('logsCard').scrollIntoView({ behavior: 'smooth' });
    } catch (error) {
        console.error('Error fetching logs:', error);
        showToast('Error fetching logs: ' + error.message, 'error');
    }
}

function displayLogs(logs) {
    if (!logs || logs.length === 0) {
        document.getElementById('logsList').innerHTML = `
            <div class="text-center text-muted py-4">
                <i class="fa fa-inbox fa-2x mb-2"></i>
                <p>No email logs found yet</p>
            </div>
        `;
        return;
    }
    
    const logsHtml = logs.map(log => {
        const statusClass = log.status === 'sent' ? 'success' : 'danger';
        const timestamp = new Date(log.created_at).toLocaleString();
        
        return `
            <div class="border-bottom py-2">
                <div class="d-flex justify-content-between align-items-start">
                    <div>
                        <span class="badge bg-${statusClass}">${log.status.toUpperCase()}</span>
                        <strong>${log.recipient_email}</strong>
                        <br>
                        <small class="text-muted">${log.subject}</small>
                    </div>
                    <small class="text-muted">${timestamp}</small>
                </div>
                ${log.error_message ? `<div class="text-danger small mt-1">Error: ${log.error_message}</div>` : ''}
            </div>
        `;
    }).join('');
    
    document.getElementById('logsList').innerHTML = logsHtml;
}

function hideLogs() {
    document.getElementById('logsCard').style.display = 'none';
}

function showToast(message, type = 'info') {
    const toast = document.getElementById('emailToast');
    const toastBody = document.getElementById('toastMessage');
    
    // Set message and styling based on type
    toastBody.textContent = message;
    toast.className = 'toast align-items-center border-0';
    
    switch (type) {
        case 'success':
            toast.classList.add('text-white', 'bg-success');
            break;
        case 'error':
            toast.classList.add('text-white', 'bg-danger');
            break;
        case 'warning':
            toast.classList.add('text-dark', 'bg-warning');
            break;
        default:
            toast.classList.add('text-white', 'bg-info');
    }
    
    // Show the toast
    const bsToast = new bootstrap.Toast(toast);
    bsToast.show();
}
</script>
{% endblock %}