// LoginPage.tsx
import React, { useState, useEffect } from 'react';
import { msalInstance, loginRequest } from './msalConfig';
import type { User } from './types';

interface LoginPageProps {
    onLogin: (user: User) => void;
}

const LoginPage: React.FC<LoginPageProps> = ({ onLogin }) => {
    const [isLoading, setIsLoading] = useState(false);
    const [error, setError] = useState<string | null>(null);

    useEffect(() => {
        // Gérer le callback après redirection Microsoft
        msalInstance.handleRedirectPromise()
            .then(async (response) => {
                if (response) {
                    console.log('✅ Authentification réussie');
                    await handleAuthSuccess(response.account.username);
                }
            })
            .catch((error) => {
                console.error('❌ Erreur auth:', error);
                setError('Erreur lors de l\'authentification');
            });
    }, []);

    const handleAuthSuccess = async (email: string) => {
        setIsLoading(true);
        setError(null);

        try {
            // Vérifier l'utilisateur dans la base de données via le backend
            const response = await fetch('/auth/verify', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ email }),
            });

            const data = await response.json();

            if (response.ok && data.valid) {
                localStorage.setItem('user', JSON.stringify(data.user));
                onLogin(data.user);
            } else {
                setError('Utilisateur non autorisé. Contactez l\'administrateur.');
            }
        } catch (err) {
            setError('Erreur de connexion au serveur');
            console.error(err);
        } finally {
            setIsLoading(false);
        }
    };

    const handleMicrosoftLogin = async () => {
        setIsLoading(true);
        setError(null);

        try {
            await msalInstance.loginRedirect(loginRequest);
        } catch (err: any) {
            setError(err.message || 'Erreur lors de la connexion');
            setIsLoading(false);
            console.error(err);
        }
    };

    return (
        <div style={styles.container}>
            {/* Panneau gauche - Branding */}
            <div style={styles.leftPanel}>
                <div style={styles.brandContent}>
                    <div style={styles.logoContainer}>
                        <svg width="72" height="72" viewBox="0 0 72 72" fill="none">
                            <rect width="72" height="72" rx="16" fill="rgba(255,255,255,0.15)" />
                            <path
                                d="M22 36L32 46L50 28"
                                stroke="#fff"
                                strokeWidth="5"
                                strokeLinecap="round"
                                strokeLinejoin="round"
                            />
                        </svg>
                    </div>

                    <h1 style={styles.brandTitle}>Suivi Évaluations</h1>
                    <p style={styles.brandSubtitle}>Plateforme de Gestion des Formations</p>

                    <div style={styles.features}>
                        {[
                            'Suivi en temps réel des évaluations',
                            'Gestion centralisée des apprenants',
                            'Collaboration formateurs et RRE'
                        ].map((feature, index) => (
                            <div key={index} style={styles.featureItem}>
                                <svg width="22" height="22" viewBox="0 0 22 22" fill="none">
                                    <circle cx="11" cy="11" r="10" stroke="#fff" strokeWidth="1.5" opacity="0.8" />
                                    <path d="M7 11l3 3 5-5" stroke="#fff" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                                </svg>
                                <span>{feature}</span>
                            </div>
                        ))}
                    </div>
                </div>
            </div>

            {/* Panneau droit - Connexion */}
            <div style={styles.rightPanel}>
                <div style={styles.loginCard}>
                    <div style={styles.cardHeader}>
                        <h2 style={styles.cardTitle}>Bienvenue</h2>
                        <p style={styles.cardSubtitle}>
                            Connectez-vous avec votre compte Microsoft 365 professionnel
                        </p>
                    </div>

                    <div style={styles.cardBody}>
                        {error && (
                            <div style={styles.errorAlert}>
                                <svg width="20" height="20" viewBox="0 0 20 20" fill="none">
                                    <circle cx="10" cy="10" r="9" stroke="#ef4444" strokeWidth="2" />
                                    <path d="M10 6v4M10 14h.01" stroke="#ef4444" strokeWidth="2" strokeLinecap="round" />
                                </svg>
                                <span>{error}</span>
                            </div>
                        )}

                        <div style={styles.microsoftIconWrapper}>
                            <svg width="80" height="80" viewBox="0 0 23 23" fill="none">
                                <rect x="1" y="1" width="10" height="10" fill="#f25022" />
                                <rect x="12" y="1" width="10" height="10" fill="#7fba00" />
                                <rect x="1" y="12" width="10" height="10" fill="#00a4ef" />
                                <rect x="12" y="12" width="10" height="10" fill="#ffb900" />
                            </svg>
                        </div>

                        <button
                            onClick={handleMicrosoftLogin}
                            disabled={isLoading}
                            style={{
                                ...styles.microsoftButton,
                                ...(isLoading ? styles.microsoftButtonLoading : {})
                            }}
                            onMouseEnter={(e) => {
                                if (!isLoading) {
                                    e.currentTarget.style.transform = 'translateY(-2px)';
                                    e.currentTarget.style.boxShadow = '0 8px 25px rgba(0, 120, 212, 0.35)';
                                }
                            }}
                            onMouseLeave={(e) => {
                                e.currentTarget.style.transform = 'translateY(0)';
                                e.currentTarget.style.boxShadow = '0 4px 15px rgba(0, 120, 212, 0.25)';
                            }}
                        >
                            {isLoading ? (
                                <>
                                    <div style={styles.spinner} />
                                    <span>Connexion en cours...</span>
                                </>
                            ) : (
                                <>
                                    <svg width="20" height="20" viewBox="0 0 23 23" fill="none">
                                        <rect x="1" y="1" width="10" height="10" fill="#f25022" />
                                        <rect x="12" y="1" width="10" height="10" fill="#7fba00" />
                                        <rect x="1" y="12" width="10" height="10" fill="#00a4ef" />
                                        <rect x="12" y="12" width="10" height="10" fill="#ffb900" />
                                    </svg>
                                    <span>Se connecter avec Microsoft 365</span>
                                    <svg width="18" height="18" viewBox="0 0 20 20" fill="none">
                                        <path
                                            d="M5 10h10M12 7l3 3-3 3"
                                            stroke="currentColor"
                                            strokeWidth="2"
                                            strokeLinecap="round"
                                            strokeLinejoin="round"
                                        />
                                    </svg>
                                </>
                            )}
                        </button>

                        <p style={styles.securityNote}>
                            <svg width="16" height="16" viewBox="0 0 20 20" fill="none" style={{ flexShrink: 0 }}>
                                <path
                                    d="M10 2L3 6v4c0 4.5 3 8.5 7 10 4-1.5 7-5.5 7-10V6l-7-4z"
                                    stroke="#22c55e"
                                    strokeWidth="1.5"
                                    fill="none"
                                />
                                <path
                                    d="M7 10l2 2 4-4"
                                    stroke="#22c55e"
                                    strokeWidth="1.5"
                                    strokeLinecap="round"
                                    strokeLinejoin="round"
                                />
                            </svg>
                            <span>Connexion sécurisée via authentification Microsoft</span>
                        </p>
                    </div>

                    <div style={styles.cardFooter}>
                        <p style={styles.footerText}>
                            Besoin d'aide ? <a href="#" style={styles.footerLink}>Contactez le support technique</a>
                        </p>
                    </div>
                </div>
            </div>

            <style>{`
                @keyframes spin {
                    0% { transform: rotate(0deg); }
                    100% { transform: rotate(360deg); }
                }
                @keyframes fadeIn {
                    from { opacity: 0; transform: translateY(20px); }
                    to { opacity: 1; transform: translateY(0); }
                }
            `}</style>
        </div>
    );
};

const styles: { [key: string]: React.CSSProperties } = {
    container: {
        display: 'flex',
        minHeight: '100vh',
        fontFamily: "'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif",
    },
    leftPanel: {
        flex: '1',
        background: 'linear-gradient(135deg, #0078d4 0%, #005a9e 50%, #004578 100%)',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        padding: '3rem',
        position: 'relative',
        overflow: 'hidden',
    },
    brandContent: {
        color: '#fff',
        maxWidth: '420px',
        zIndex: 1,
    },
    logoContainer: {
        marginBottom: '2rem',
    },
    brandTitle: {
        fontSize: '2.5rem',
        fontWeight: 700,
        marginBottom: '0.75rem',
        letterSpacing: '-0.02em',
    },
    brandSubtitle: {
        fontSize: '1.1rem',
        opacity: 0.9,
        marginBottom: '3rem',
        fontWeight: 400,
    },
    features: {
        display: 'flex',
        flexDirection: 'column',
        gap: '1.25rem',
    },
    featureItem: {
        display: 'flex',
        alignItems: 'center',
        gap: '1rem',
        fontSize: '1rem',
        opacity: 0.95,
    },
    rightPanel: {
        flex: '1',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        padding: '3rem',
        backgroundColor: '#f8fafc',
    },
    loginCard: {
        backgroundColor: '#fff',
        borderRadius: '20px',
        boxShadow: '0 25px 50px -12px rgba(0, 0, 0, 0.1)',
        padding: '3rem',
        width: '100%',
        maxWidth: '440px',
        animation: 'fadeIn 0.5s ease-out',
    },
    cardHeader: {
        textAlign: 'center',
        marginBottom: '2.5rem',
    },
    cardTitle: {
        fontSize: '2rem',
        fontWeight: 700,
        color: '#1e293b',
        marginBottom: '0.75rem',
    },
    cardSubtitle: {
        fontSize: '1rem',
        color: '#64748b',
        lineHeight: 1.6,
    },
    cardBody: {
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        gap: '1.5rem',
    },
    errorAlert: {
        display: 'flex',
        alignItems: 'center',
        gap: '10px',
        width: '100%',
        padding: '12px 16px',
        backgroundColor: '#fee2e2',
        border: '1px solid #fecaca',
        borderRadius: '8px',
        color: '#991b1b',
        fontSize: '0.875rem',
    },
    microsoftIconWrapper: {
        padding: '1.5rem',
        backgroundColor: '#f1f5f9',
        borderRadius: '16px',
        marginBottom: '0.5rem',
    },
    microsoftButton: {
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        gap: '12px',
        width: '100%',
        padding: '16px 24px',
        fontSize: '1rem',
        fontWeight: 600,
        color: '#fff',
        backgroundColor: '#0078d4',
        border: 'none',
        borderRadius: '12px',
        cursor: 'pointer',
        transition: 'all 0.2s ease',
        boxShadow: '0 4px 15px rgba(0, 120, 212, 0.25)',
    },
    microsoftButtonLoading: {
        opacity: 0.8,
        cursor: 'not-allowed',
    },
    spinner: {
        width: '22px',
        height: '22px',
        border: '3px solid rgba(255,255,255,0.3)',
        borderTopColor: '#fff',
        borderRadius: '50%',
        animation: 'spin 0.8s linear infinite',
    },
    securityNote: {
        display: 'flex',
        alignItems: 'center',
        gap: '8px',
        fontSize: '0.875rem',
        color: '#64748b',
        marginTop: '0.5rem',
    },
    cardFooter: {
        marginTop: '2.5rem',
        paddingTop: '1.5rem',
        borderTop: '1px solid #e2e8f0',
        textAlign: 'center',
    },
    footerText: {
        fontSize: '0.875rem',
        color: '#64748b',
    },
    footerLink: {
        color: '#0078d4',
        textDecoration: 'none',
        fontWeight: 500,
    },
};

export default LoginPage;