{% extends "base.html" %}

{% block title %}Configuration Outlook - GMAO Collège{% endblock %}

{% block content %}
<div class="container-fluid">
    <div class="row mb-4">
        <div class="col">
            <h1>⚙️ Configuration Outlook</h1>
            <p class="text-muted">Ajoutez et gérez vos comptes Outlook pour synchroniser vos emails</p>
        </div>
    </div>
    
    <!-- Formulaire d'ajout de compte -->
    <div class="row mb-4">
        <div class="col-md-6">
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0">Ajouter un nouveau compte Outlook</h5>
                </div>
                <div class="card-body">
                    <form id="addAccountForm">
                        <div class="mb-3">
                            <label for="email" class="form-label">Email Outlook</label>
                            <input type="email" class="form-control" id="email" required 
                                   placeholder="votre.email@departement77.fr">
                            <div class="form-text">Entrez l'email complet de votre compte Outlook</div>
                        </div>
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-plus"></i> Configurer le compte
                        </button>
                    </form>
                </div>
            </div>
        </div>
        
        <div class="col-md-6">
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0">Instructions</h5>
                </div>
                <div class="card-body">
                    <ol>
                        <li>Entrez votre email Outlook complet</li>
                        <li>Cliquez sur "Configurer le compte"</li>
                        <li>Un code s'affichera - notez-le</li>
                        <li>Allez sur Microsoft.com et entrez le code</li>
                        <li>Connectez-vous à votre compte</li>
                        <li>Attendez la confirmation de synchronisation</li>
                    </ol>
                    
                    <div class="alert alert-info mt-3">
                        <i class="fas fa-info-circle"></i>
                        <strong>Important:</strong> Vous devez utiliser votre email professionnel du Département 77.
                    </div>
                    
                    <div class="alert alert-warning mt-2">
                        <i class="fas fa-exclamation-triangle"></i>
                        Assurez-vous d'avoir les droits nécessaires sur votre compte Outlook.
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Liste des comptes existants -->
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">Mes comptes configurés</h5>
                    <button class="btn btn-outline-primary btn-sm" onclick="location.reload()">
                        <i class="fas fa-sync"></i> Actualiser
                    </button>
                </div>
                <div class="card-body">
                    {% if accounts %}
                        <div class="table-responsive">
                            <table class="table table-striped">
                                <thead>
                                    <tr>
                                        <th>Email</th>
                                        <th>Statut</th>
                                        <th>Client ID</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {% for account in accounts %}
                                    <tr>
                                        <td>
                                            <i class="fas fa-envelope text-primary"></i>
                                            {{ account.email }}
                                        </td>
                                        <td>
                                            {% if account.is_active and account.connection_status == 'active' %}
                                                <span class="badge bg-success">Actif</span>
                                                {% if account.last_connected_at %}
                                                    <small class="text-muted ms-2">
                                                        Dernière connexion: {{ account.last_connection_at|datetime_fmt }}
                                                    </small>
                                                {% endif %}
                                            {% elif account.connection_status == 'pending' %}
                                                <span class="badge bg-warning">En attente</span>
                                            {% elif account.connection_status == 'error' %}
                                                <span class="badge bg-danger">Erreur</span>
                                            {% else %}
                                                <span class="badge bg-secondary">Inactif</span>
                                            {% endif %}
                                        </td>
                                        <td>
                                            <code class="small">{{ account.client_id }}</code>
                                        </td>
                                        <td>
                                            <div class="btn-group btn-group-sm">
                                                {% if account.connection_status == 'pending' %}
                                                    <button onclick="retryAuth({{ account.id }})" 
                                                            class="btn btn-outline-warning" title="Recommencer">
                                                        <i class="fas fa-redo"></i>
                                                    </button>
                                                {% endif %}
                                                
                                                {% if account.is_active and account.connection_status == 'active' %}
                                                    <button onclick="testConnection({{ account.id }})" 
                                                            class="btn btn-outline-info" title="Tester la connexion">
                                                        <i class="fas fa-plug"></i>
                                                    </button>
                                                    <button onclick="syncMails({{ account.id }})" 
                                                            class="btn btn-outline-success" title="Synchroniser">
                                                        <i class="fas fa-sync"></i>
                                                    </button>
                                                    <a href="{{ url_for('outlook_pages.account_detail', account_id=account.id) }}" 
                                                       class="btn btn-outline-primary" title="Voir les mails">
                                                        <i class="fas fa-envelope-open"></i>
                                                    </a>
                                                {% endif %}
                                                
                                                <button onclick="deleteAccount({{ account.id }})" 
                                                        class="btn btn-outline-danger" title="Supprimer">
                                                    <i class="fas fa-trash"></i>
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                    {% endfor %}
                                </tbody>
                            </table>
                        </div>
                    {% else %}
                        <div class="text-center py-4">
                            <i class="fas fa-envelope-open-text fa-3x text-muted mb-3"></i>
                            <h5>Aucun compte configuré</h5>
                            <p class="text-muted">Commencez par ajouter votre premier compte Outlook.</p>
                        </div>
                    {% endif %}
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Modal d'authentification -->
<div class="modal fade" id="authModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Configuration du compte Outlook</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div id="authContent">
                    <p class="text-center mb-3">
                        <i class="fas fa fa-mobile-alt fa-2x text-primary"></i>
                    </p>
                    <h6 class="text-center mb-3">Connectez-vous à votre compte Outlook</h6>
                    <div class="text-center my-4">
                        <h2 class="display-4 text-primary mb-3" id="userCode"></h2>
                        <p class="mb-3">Entrez ce code sur le site Microsoft :</p>
                        <a href="#" id="authLink" target="_blank" class="btn btn-primary btn-lg">
                            <i class="fas fa-external-link-alt"></i> Se connecter à Microsoft
                        </a>
                    </div>
                    <div class="alert alert-info">
                        <i class="fas fa-info-circle"></i>
                        Le code expire dans <span id="countdown">15</span> minutes. Ne fermez pas cette fenêtre.
                    </div>
                </div>
                
                <div id="authStatus" style="display: none;">
                    <div class="text-center">
                        <div class="spinner-border text-primary" role="status">
                            <span class="visually-hidden">Chargement...</span>
                        </div>
                        <p class="mt-3">En attente de la confirmation...</p>
                        <small class="text-muted">
                            Veuillez compléter la connexion sur le site Microsoft
                        </small>
                    </div>
                </div>
                
                <div id="authSuccess" style="display: none;">
                    <div class="text-center">
                        <i class="fas fa-check-circle fa-2x text-success mb-3"></i>
                        <h6>Connexion réussie !</h6>
                        <p class="text-muted">Le compte est en cours de configuration...</p>
                    </div>
                </div>
                
                <div id="authError" style="display: none;">
                    <div class="text-center">
                        <i class="fas fa-exclamation-circle fa-2x text-danger mb-3"></i>
                        <h6>Erreur d'authentification</h6>
                        <p class="text-muted" id="errorMessage"></p>
                        <button class="btn btn-outline-primary" onclick="closeModal()">Fermer</button>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Annuler</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
let countdownInterval;
let currentAccountId = null;

document.getElementById('addAccountForm').addEventListener('submit', function(e) {
    e.preventDefault();
    
    const email = document.getElementById('email').value;
    
    fetch('/outlook/api/start-auth', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({ email: email })
    })
    .then(response => response.json())
    .then(data => {
        if (data.error) {
            alert('Erreur: ' + data.error);
        } else {
            currentAccountId = data.account_id;
            showAuthModal(data);
        }
    })
    .catch(error => {
        alert('Erreur réseau: ' + error);
    });
});

function showAuthModal(data) {
    const modal = new bootstrap.Modal(document.getElementById('authModal'));
    
    document.getElementById('userCode').textContent = data.user_code;
    document.getElementById('authLink').href = data.verification_uri;
    document.getElementById('authContent').style.display = 'block';
    document.getElementById('authStatus').style.display = 'none';
    document.getElementById('authSuccess').style.display = 'none';
    document.getElementById('authError').style.display = 'none';
    
    modal.show();
    
    // Démarrer le décompte
    let timeLeft = Math.floor(data.expires_in / 60);
    document.getElementById('countdown').textContent = timeLeft;
    
    countdownInterval = setInterval(() => {
        timeLeft--;
        document.getElementById('countdown').textContent = timeLeft;
        
        if (timeLeft <= 0) {
            clearInterval(countdownInterval);
            showErrorLe('Le code a expiré. Veuillez recommencer.');
        }
    }, 1000);
    
    // Vérifier périodiquement la connexion
    checkAuthStatus();
}

function checkAuthStatus() {
    const checkInterval = setInterval(() => {
        fetch(`/outlook/api/test-connection/${currentAccountId}`)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    clearInterval(checkInterval);
                    clearInterval(countdownInterval);
                    
                    document.getElementById('authContent').style.display = 'none';
                    document.getElementById('authStatus').style.display = 'none';
                    document.getElementById('authSuccess').style.display = 'block';
                    
                    setTimeout(() => {
                        bootstrap.Modal.getInstance(document.getElementById('authModal')).hide();
                        location.reload();
                    }, 2000);
                }
            })
            .catch(error => {
                // Ignorer les erreurs pendant l'attente
            });
    }, 3000);
}

function retryAuth(accountId) {
    // Simuler un retry (en réalité, on devrait relancer le flux)
    alert('Fonctionnalité de retry à implémenter');
}

function testConnection(accountId) {
    fetch(`/outlook/api/test-connection/${accountId}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert('Connexion OK');
                location.reload();
            } else {
                alert('Connexion échouée: ' + data.error);
            }
        })
        .catch(error => {
            alert('Erreur réseau: ' + error);
        });
}

function syncMails(accountId) {
    if (confirm('Synchroniser les derniers mails ?')) {
        fetch(`/outlook/api/sync-mails/${accountId}`, {method: 'POST'})
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert(data.message);
                    location.reload();
                } else {
                    alert('Erreur: ' + data.error);
                }
            })
            .catch(error => {
                alert('Erreur réseau: ' + error);
            });
    }
}

function deleteAccount(accountId) {
    if (confirm('Supprimer ce compte Outlook ?')) {
        fetch(`/outlook/api/delete-account/${accountId}`, {
            method: 'DELETE'
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert('Compte supprimé');
                location.reload();
            } else {
                alert('Erreur: ' + data.error);
            }
        })
        .catch(error => {
            alert('Erreur réseau: ' + error);
        });
    }
}

function closeModal() {
    bootstrap.Modal.getInstance(document.getElementById('authModal')).hide();
    if (countdownInterval) {
        clearInterval(countdownInterval);
    }
}

function showError(message) {
    document.getElementById('errorMessage').textContent = message;
    document.getElementById('authContent').style.display = 'none';
    document.getElementById('authStatus').style.display = 'none';
    document.getElementById('authSuccess').style.display = 'none';
    document.getElementById('authError').style.display = 'block';
}
</script>
{% endblock %}
