/**
 * Admin Login Module
 * Handles authentication, session management, and redirection
 */

const AdminLogin = {
    // Configuration
    config: {
        apiUrl: '/est-concours/model/api/candidat.php',
        maxAttempts: 3,
        redirectUrl: '/est-concours/app/view/candidat/inscription/create/index.php'
    },

    // DOM Elements
    elements: {
        form: null,
        emailInput: null,
        passwordInput: null,
        loginBtn: null,
        messageContainer: null,
        loadingSpinner: null
    },

    /**
     * Initialize the login module
     */
    init() {
        this.cacheElements();
        this.bindEvents();
        this.setupAutoFocus();
    },

    /**
     * Cache DOM elements
     */
    cacheElements() {
        this.elements.form = document.getElementById('loginForm');
        this.elements.emailInput = document.getElementById('email');
        this.elements.passwordInput = document.getElementById('password');
        this.elements.loginBtn = document.querySelector('#loginBtn');
        this.elements.messageContainer = this.createMessageContainer();

        // Create loading spinner
        this.elements.loadingSpinner = document.createElement('span');
        this.elements.loadingSpinner.className = 'spinner-border spinner-border-sm';
        this.elements.loadingSpinner.setAttribute('role', 'status');
        this.elements.loadingSpinner.setAttribute('aria-hidden', 'true');
    },

    /**
     * Create message container for alerts
     */
    createMessageContainer() {
        const container = document.createElement('div');
        container.id = 'loginMessage';
        container.className = 'mb-3';

        // Insert after the logo
        const logo = document.querySelector('.logo');
        if (logo) {
            logo.parentNode.insertBefore(container, logo.nextSibling);
        } else {
            const form = document.querySelector('form');
            if (form) {
                form.parentNode.insertBefore(container, form);
            }
        }

        return container;
    },

    /**
     * Bind event listeners
     */
    bindEvents() {
        // Form submission
        if (this.elements.form) {
            this.elements.form.addEventListener('submit', (e) => {
                e.preventDefault();
                this.handleLogin();
            });
        }

        // Enter key on password field
        if (this.elements.passwordInput) {
            this.elements.passwordInput.addEventListener('keypress', (e) => {
                if (e.key === 'Enter') {
                    e.preventDefault();
                    this.handleLogin();
                }
            });
        }

        // Real-time validation on blur
        document.querySelectorAll('input[required]').forEach(input => {
            input.addEventListener('blur', function () {
                this.classList.toggle('is-invalid', !this.value.trim());
                const errorId = this.id + '-error';
                const errorEl = document.getElementById(errorId);
                if (errorEl) {
                    errorEl.classList.toggle('show', !this.value.trim());
                }
            });
        });
    },

    /**
     * Setup auto-focus on email input
     */
    setupAutoFocus() {
        if (this.elements.emailInput) {
            this.elements.emailInput.focus();
        }
    },

    /**
     * Handle login attempt
     */
    async handleLogin() {
        // Validate form
        if (!this.validateForm()) {
            return;
        }

        // Get credentials
        const email = this.elements.emailInput.value.trim();
        const password = this.elements.passwordInput.value.trim();

        // Show loading state
        this.setLoadingState(true);

        try {
            // Send login request
            const response = await this.sendLoginRequest(email, password);

            // Handle response
            if (response.success) {
                // Login successful - store session and redirect
               await this.handleSuccess(response);
            } else {
                // Login failed
                this.handleError(response);
            }
        } catch (error) {
            console.error('Login error:', error);
            this.showMessage('error', 'Une erreur est survenue. Veuillez réessayer.');
        } finally {
            this.setLoadingState(false);
        }
    },

    /**
     * Send login request to API
     */
    async sendLoginRequest(email, password) {
        const response = await fetch(`${this.config.apiUrl}?action=login`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            },
            body: JSON.stringify({
                email: email,
                password: password
            })
        });

        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }

        return await response.json();
    },

    /**
     * Handle successful login
     */
   async handleSuccess(data) {
        // Store user data in sessionStorage for client-side use
        try {
            const userData = {
                id: data.id,
                email: data.email,
                nom: data.nom,
                prenom: data.prenom,
                cin: data.cin,
                phone: data.phone,
                loginTime: new Date().toISOString()
            };
            sessionStorage.setItem('candidat', JSON.stringify(userData));

            // Also could set a cookie or session token
            document.cookie = `admin_session=true; path=/; max-age=${60 * 60 * 24}`; // 1 day
        } catch (e) {
            console.warn('Could not store session data:', e);
        }

        // Show success message
        this.showMessage('success', 'Connexion réussie ! Redirection en cours...');

        // Show success message
        this.showMessage('success', 'Connexion réussie ! Vérification de vos inscriptions...');

        try {
            // Check candidat inscriptions to determine redirect
            const candidatId = data.id;
            const response = await fetch(`${this.config.apiUrl}?action=check_inscriptions&candidat_id=${candidatId}`);
            const result = await response.json();

            if (result.success && result.data) {
                let redirectUrl = result.data.redirect_url;
/*
                if (redirectUrl && !redirectUrl.includes('candidat_id=')) {
                    const separator = redirectUrl.includes('?') ? '&' : '?';
                    redirectUrl += `${separator}candidat_id=${candidatId}`;
                }
*/

                console.log("haaa url redirect " +redirectUrl);
              setTimeout(() => {window.location.href = redirectUrl;}, 800);
            } else {
                // Fallback - redirect to create page
                setTimeout(() => {window.location.href = this.config.redirectUrl ;}, 800);
            }
        } catch (error) {
            console.error('Error checking inscriptions:', error);
            // Fallback - redirect to create page
            setTimeout(() => {
                window.location.href = this.config.redirectUrl;
            }, 800);
        }

    },

    /**
     * Handle login error
     */
    handleError(response) {
        const message = response.message || 'Email ou mot de passe incorrect';

        // Check if account is blocked
        if (message.toLowerCase().includes('bloqué')) {
            this.showMessage('error', '🚫 ' + message);
            this.elements.loginBtn.disabled = true;
            // Optionally show a contact admin button
            this.showContactAdmin();
        } else {
            this.showMessage('warning', '⚠️ ' + message);
            // Highlight the problematic fields
            this.highlightError();
        }

        // Clear password field for security
        this.elements.passwordInput.value = '';
        this.elements.passwordInput.focus();
    },

    /**
     * Validate form fields
     */
    validateForm() {
        const email = this.elements.emailInput.value.trim();
        const password = this.elements.passwordInput.value.trim();
        let isValid = true;

        // Reset error states
        this.elements.emailInput.classList.remove('is-invalid');
        this.elements.passwordInput.classList.remove('is-invalid');
        document.getElementById('email-error')?.classList.remove('show');
        document.getElementById('password-error')?.classList.remove('show');

        // Validate email
        if (!email) {
            this.elements.emailInput.classList.add('is-invalid');
            document.getElementById('email-error')?.classList.add('show');
            isValid = false;
        }

        // Validate password
        if (!password) {
            this.elements.passwordInput.classList.add('is-invalid');
            document.getElementById('password-error')?.classList.add('show');
            isValid = false;
        }

        return isValid;
    },

    /**
     * Set loading state on button
     */
    setLoadingState(loading) {
        const btn = this.elements.loginBtn;
        if (!btn) return;

        if (loading) {
            btn.disabled = true;
            btn.innerHTML = `
                <span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
                Connexion en cours...
            `;
        } else {
            btn.disabled = false;
            btn.innerHTML = `
                <i class="fas fa-sign-in-alt"></i> Se Connecter
            `;
        }
    },

    /**
     * Show message in the container
     */
    showMessage(type, message) {
        const container = this.elements.messageContainer;
        if (!container) return;

        const alertClass = {
            'success': 'alert-success',
            'error': 'alert-error',
            'warning': 'alert-warning',
            'info': 'alert-info'
        };

        const iconMap = {
            'success': 'fa-check-circle',
            'error': 'fa-times-circle',
            'warning': 'fa-exclamation-triangle',
            'info': 'fa-info-circle'
        };

        container.innerHTML = `
            <div class="alert alert-custom ${alertClass[type] || 'alert-info'} alert-dismissible fade show" role="alert">
                <i class="fas ${iconMap[type] || 'fa-info-circle'}"></i>
                <span>${message}</span>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        `;
    },

    /**
     * Highlight error fields
     */
    highlightError() {
        this.elements.emailInput.classList.add('is-invalid');
        this.elements.passwordInput.classList.add('is-invalid');
    },

    /**
     * Show contact admin option when account is blocked
     */
    showContactAdmin() {
        const container = this.elements.messageContainer;
        if (!container) return;

        const contactHtml = `
            <div class="mt-3 text-center">
                <small class="text-muted">
                    <i class="fas fa-phone"></i> Contactez l'administrateur au 
                    <a href="tel:+212XXXXXXXX">+212 XXXXXXXXX</a>
                </small>
            </div>
        `;

        // Append to existing message
        const existingAlert = container.querySelector('.alert');
        if (existingAlert) {
            existingAlert.insertAdjacentHTML('afterend', contactHtml);
        }
    },

    /**
     * Forgot password handler
     */
    forgotPassword() {
        const email = this.elements.emailInput.value.trim();

        if (!email) {
            this.showMessage('warning', 'Veuillez entrer votre email pour réinitialiser votre mot de passe.');
            this.elements.emailInput.focus();
            return;
        }

        // In a real application, send reset link
        this.showMessage('info', `📧 Un email de réinitialisation a été envoyé à ${email}`);
    }
};

// Initialize when DOM is ready
document.addEventListener('DOMContentLoaded', () => {
    AdminLogin.init();

    // Expose forgotPassword function globally (used in HTML)
    window.forgotPassword = function () {
        AdminLogin.forgotPassword();
    };
});

// Optional: Add CSS for the login page
const style = document.createElement('style');
style.textContent = `
    .alert-custom {
        border-radius: 6px;
        padding: 12px 15px;
        margin-bottom: 20px;
        font-size: 14px;
        display: flex;
        align-items: center;
        gap: 10px;
    }
    
    .alert-custom i {
        font-size: 18px;
        flex-shrink: 0;
    }
    
    .alert-custom.alert-error {
        background-color: #f8d7da;
        border: 1px solid #f5c6cb;
        color: #721c24;
    }
    
    .alert-custom.alert-success {
        background-color: #d4edda;
        border: 1px solid #c3e6cb;
        color: #155724;
    }
    
    .alert-custom.alert-warning {
        background-color: #fff3cd;
        border: 1px solid #ffeaa7;
        color: #856404;
    }
    
    .alert-custom.alert-info {
        background-color: #d1ecf1;
        border: 1px solid #bee5eb;
        color: #0c5460;
    }
    
    .spinner-border {
        display: inline-block;
        width: 1rem;
        height: 1rem;
        vertical-align: text-bottom;
        border: 0.2em solid currentColor;
        border-right-color: transparent;
        border-radius: 50%;
        animation: spinner-border .75s linear infinite;
    }
    
    @keyframes spinner-border {
        to { transform: rotate(360deg); }
    }
`;
document.head.appendChild(style);
