{% extends "base.html" %}
{% block title %}Ajouter un compte Outlook{% endblock %}
{% block content %}
<div class="container-fluid">
    <h1 class="h3 mb-4">Ajouter un compte Outlook</h1>
    
    <div class="row">
        <div class="col-md-6">
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0">Connexion OAuth2</h5>
                </div>
                <div class="card-body">
                    <form id="outlook-auth-form">
                        <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
                        <div class="mb-3">
                            <label class="form-label">Email professionnel</label>
                            <input type="email" name="email" id="email" class="form-control" required 
                                   placeholder="votre.email@ac-college.fr">
                            <div class="form-text">Utilisez votre email professionnel Education Nationale</div>
                        </div>
                        <button type="submit" class="btn btn-primary" id="submit-btn">
                            <span id="btn-text">Se connecter avec Outlook</span>
                            <span id="btn-spinner" class="spinner-border spinner-border-sm d-none" role="status"></span>
                        </button>
                    </form>
                    
                    <div id="auth-result" class="mt-3"></div>
                </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 professionnel</li>
                        <li>Cliquez sur "Se connecter"</li>
                        <li>Un code et un lien s'afficheront</li>
                        <li>Cliquez sur le lien Microsoft</li>
                        <li>Connectez-vous avec vos identifiants Education Nationale</li>
                        <li>Entrez le code affiché sur cette page</li>
                        <li>La connexion se finalise automatiquement</li>
                    </ol>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
let pollInterval = null;
let accountId = null;

document.getElementById('outlook-auth-form').addEventListener('submit', async function(e) {
    e.preventDefault();
    
    const email = document.getElementById('email').value;
    const btn = document.getElementById('submit-btn');
    const btnText = document.getElementById('btn-text');
    const spinner = document.getElementById('btn-spinner');
    const result = document.getElementById('auth-result');
    
    btn.disabled = true;
    btnText.textContent = 'Connexion en cours...';
    spinner.classList.remove('d-none');
    
    try {
        const response = await fetch('/outlook/api/start-auth', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({ email: email })
        });
        
        const data = await response.json();
        
        if (data.error) {
            result.innerHTML = `<div class="alert alert-danger">${data.error}</div>`;
            btn.disabled = false;
            btnText.textContent = 'Se connecter avec Outlook';
            spinner.classList.add('d-none');
        } else {
            accountId = data.account_id;
            
            // Afficher les instructions
            result.innerHTML = `
                <div class="alert alert-info">
                    <h5>Authentification requise</h5>
                    <p><strong>Code:</strong> <span class="h4 text-primary">${data.user_code}</span></p>
                    <p><a href="${data.verification_uri}" target="_blank" class="btn btn-success">
                        <i class="bi bi-box-arrow-up-right"></i> Ouvrir Microsoft
                    </a></p>
                    <p class="small text-muted">Ce code expire dans ${Math.floor(data.expires_in / 60)} minutes</p>
                </div>
                <div class="alert alert-warning mt-3" id="poll-status">
                    <span class="spinner-border spinner-border-sm"></span> En attente de l'autorisation...
                </div>
            `;
            
            btnText.textContent = 'Connexion en cours';
            
            // Démarrer le polling automatique
            startPolling(accountId);
        }
    } catch (error) {
        result.innerHTML = `<div class="alert alert-danger">Erreur: ${error.message}</div>`;
        btn.disabled = false;
        btnText.textContent = 'Se connecter avec Outlook';
        spinner.classList.add('d-none');
    }
});

function startPolling(accountId) {
    let attempts = 0;
    const maxAttempts = 60; // 5 minutes max (polling every 5 seconds)
    
    pollInterval = setInterval(async () => {
        attempts++;
        
        if (attempts > maxAttempts) {
            clearInterval(pollInterval);
            document.getElementById('poll-status').innerHTML = 
                '<span class="text-danger">Délai expiré, veuillez recommencer</span>';
            resetForm();
            return;
        }
        
        try {
            const response = await fetch(`/outlook/api/poll-auth/${accountId}`, {
                method: 'POST',
                headers: {'Content-Type': 'application/json'}
            });
            
            const data = await response.json();
            
            if (data.success) {
                clearInterval(pollInterval);
                document.getElementById('poll-status').innerHTML = 
                    '<span class="text-success"><i class="bi bi-check-circle"></i> Authentification réussie!</span>';
                
                setTimeout(() => {
                    window.location.href = '/outlook-test/';
                }, 1500);
            } else if (data.pending) {
                // Toujours en attente, continuer le polling
            } else if (data.error) {
                if (data.expired) {
                    clearInterval(pollInterval);
                    document.getElementById('poll-status').innerHTML = 
                        '<span class="text-danger">Code expiré, veuillez recommencer</span>';
                    resetForm();
                }
                // Autres erreurs: continuer le polling
            }
        } catch (error) {
            console.error('Erreur polling:', error);
        }
    }, 5000); // Polling toutes les 5 secondes
}

function resetForm() {
    const btn = document.getElementById('submit-btn');
    const btnText = document.getElementById('btn-text');
    const spinner = document.getElementById('btn-spinner');
    
    btn.disabled = false;
    btnText.textContent = 'Se connecter avec Outlook';
    spinner.classList.add('d-none');
}
</script>
{% endblock %}