import React, { createContext, useContext, useState, useEffect } from 'react';
import { useMsal } from '@azure/msal-react';
import { loginRequest, API_BASE_URL } from '../authConfig';

const AuthContext = createContext();

export const useAuth = () => {
    const context = useContext(AuthContext);
    if (!context) throw new Error('useAuth must be used within an AuthProvider');
    return context;
};

// ✅ Détection mobile améliorée
const isMobileDevice = () => {
    const ua = navigator.userAgent;
    return /iPhone|iPad|iPod|Android|webOS|BlackBerry|IEMobile|Opera Mini/i.test(ua);
};

const shouldUseRedirect = () => {
    if (isMobileDevice()) {
        return true;
    }
    return window.innerWidth < 768;
};

export const AuthProvider = ({ children }) => {
    const { instance, accounts, inProgress } = useMsal();
    const [user, setUser] = useState(null);
    const [userGroups, setUserGroups] = useState([]);
    const [isAuthorized, setIsAuthorized] = useState(false);
    const [isLoading, setIsLoading] = useState(true);

    const getApiUrl = (endpoint) => {
        const cleanEndpoint = endpoint.startsWith('/') ? endpoint.slice(1) : endpoint;
        return `${API_BASE_URL}/${cleanEndpoint}`;
    };

    // --- Vérifie l'autorisation de l'utilisateur via groupes
    const checkUserAuthorization = async (userPrincipalName, accessToken) => {
        try {
            const response = await fetch(getApiUrl('check-user-groups'), {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${accessToken}`
                },
                body: JSON.stringify({ userPrincipalName })
            });

            if (response.ok) {
                const data = await response.json();
                setUserGroups(data.groups || []);
                setIsAuthorized(data.authorized || false);
                return data;
            }
            return { authorized: false, groups: [] };
        } catch (error) {
            console.error('Erreur vérification groupes:', error);
            return { authorized: false, groups: [] };
        }
    };

    // --- Synchronisation utilisateur connecté
    const syncUserToDatabase = async (entraUser, accessToken) => {
        try {
            const response = await fetch(getApiUrl('initial-sync'), {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${accessToken}`
                },
                body: JSON.stringify(entraUser)
            });

            if (response.ok) {
                const data = await response.json();
                console.log('✅ Utilisateur synchronisé:', entraUser.userPrincipalName);
                return data;
            }
        } catch (error) {
            console.error('❌ Erreur synchronisation utilisateur:', error);
        }
        return null;
    };

    // --- Full sync admin
    const fullSyncDatabase = async (accessToken) => {
        try {
            const response = await fetch(getApiUrl('initial-sync'), {
                method: 'POST',
                headers: { 'Authorization': `Bearer ${accessToken}` }
            });

            if (response.ok) {
                const data = await response.json();
                console.log('✅ Full sync terminée:', data);
                return data;
            }
        } catch (error) {
            console.error('❌ Erreur full sync:', error);
        }
        return null;
    };

    // --- Gestion login réussi
    const handleSuccessfulAuth = async (authResponse) => {
        try {
            console.log('🔐 Traitement authentification réussie...');
            const account = authResponse.account;
            const accessToken = authResponse.accessToken;

            if (!account || !accessToken) {
                throw new Error('Données d\'authentification incomplètes');
            }

            let entraUser = {
                id: account.homeAccountId,
                displayName: account.name,
                userPrincipalName: account.username,
                mail: account.username
            };

            // Appel Graph API pour enrichir les données
            console.log('📞 Appel Graph API...');
            try {
                const graphResponse = await fetch('https://graph.microsoft.com/v1.0/me', {
                    headers: { 'Authorization': `Bearer ${accessToken}` }
                });

                if (graphResponse.ok) {
                    const graphData = await graphResponse.json();
                    entraUser = { ...entraUser, ...graphData };
                    console.log('✅ Données Graph récupérées');
                }
            } catch (graphError) {
                console.warn('⚠️ Erreur Graph API:', graphError);
            }

            // Synchronisation utilisateur
            console.log('🔄 Synchronisation utilisateur...');
            const syncResult = await syncUserToDatabase(entraUser, accessToken);

            if (syncResult?.role === 'Admin') {
                console.log('👑 Admin détecté → lancement full sync...');
                await fullSyncDatabase(accessToken);
            }

            // Vérification des groupes
            console.log('🔍 Vérification groupes...');
            const authResult = await checkUserAuthorization(entraUser.userPrincipalName, accessToken);

            if (authResult.authorized) {
                console.log('✅ Utilisateur autorisé');

                const userData = {
                    id: syncResult?.localUserId || entraUser.id,
                    CollaborateurADId: syncResult?.localUserId,
                    entraUserId: entraUser.id,
                    name: entraUser.displayName,
                    prenom: entraUser.givenName || entraUser.displayName?.split(' ')[0] || '',
                    nom: entraUser.surname || entraUser.displayName?.split(' ')[1] || '',
                    email: entraUser.mail || entraUser.userPrincipalName,
                    userPrincipalName: entraUser.userPrincipalName,
                    role: syncResult?.role || 'Employe',
                    service: syncResult?.service || entraUser.department || 'Non défini',
                    jobTitle: entraUser.jobTitle,
                    department: entraUser.department,
                    officeLocation: entraUser.officeLocation,
                    typeContrat: syncResult?.typeContrat || '37h',
                    dateEntree: syncResult?.dateEntree || null,
                    groups: authResult.groups
                };

                setUser(userData);
                setIsAuthorized(true);
                console.log('✅ Connexion réussie:', userData.email);

            } else {
                console.error('❌ Utilisateur non autorisé');
                throw new Error('Utilisateur non autorisé - pas membre des groupes requis');
            }
        } catch (error) {
            console.error('❌ Erreur handleSuccessfulAuth:', error);
            throw error;
        } finally {
            setIsLoading(false);
        }
    };

    // ✅ SIMPLIFIÉ : L'initialisation MSAL est déjà faite dans main.jsx
    useEffect(() => {
        const processAuthentication = async () => {
            // Attendre que MSAL finisse ses opérations en cours
            if (inProgress !== 'none') {
                console.log('⏳ MSAL inProgress:', inProgress);
                return;
            }

            console.log('🌐 AuthContext - Vérification session');
            console.log('📊 Comptes MSAL:', accounts.length);

            // Si un compte existe, récupérer le token et traiter l'auth
            if (accounts.length > 0) {
                const account = accounts[0];
                console.log('✅ Compte trouvé:', account.username);

                try {
                    // Définir le compte actif
                    instance.setActiveAccount(account);

                    // Acquérir un token silencieusement
                    const tokenResponse = await instance.acquireTokenSilent({
                        ...loginRequest,
                        account: account
                    });

                    console.log('✅ Token acquis silencieusement');
                    await handleSuccessfulAuth(tokenResponse);

                } catch (error) {
                    console.error('❌ Erreur acquireTokenSilent:', error);

                    // Si interaction requise, relancer l'auth
                    if (error.name === 'InteractionRequiredAuthError' ||
                        error.errorCode === 'consent_required' ||
                        error.errorCode === 'interaction_required' ||
                        error.errorCode === 'login_required') {

                        console.log('🔄 Interaction requise, relancement...');
                        try {
                            if (shouldUseRedirect()) {
                                await instance.acquireTokenRedirect({
                                    ...loginRequest,
                                    account: account
                                });
                            } else {
                                const response = await instance.acquireTokenPopup({
                                    ...loginRequest,
                                    account: account
                                });
                                await handleSuccessfulAuth(response);
                            }
                        } catch (interactionError) {
                            console.error('❌ Erreur interaction:', interactionError);
                            setIsLoading(false);
                        }
                    } else {
                        setIsLoading(false);
                    }
                }
            } else {
                // Pas de compte = utilisateur non connecté
                console.log('ℹ️ Aucun compte MSAL - utilisateur non connecté');
                setIsLoading(false);
            }
        };

        processAuthentication();
    }, [instance, accounts, inProgress]);

    // --- Connexion classique
    const login = async (email, password) => {
        try {
            const response = await fetch(getApiUrl('login'), {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ email, mot_de_passe: password })
            });

            if (!response.ok) throw new Error('Erreur de connexion');

            const data = await response.json();
            if (data.success) {
                setUser({
                    id: data.user.id,
                    name: `${data.user.prenom} ${data.user.nom}`,
                    prenom: data.user.prenom,
                    nom: data.user.nom,
                    email: data.user.email,
                    role: data.user.role || 'Employe',
                    service: data.user.service || 'Non défini'
                });
                setIsAuthorized(true);
                return true;
            }
            return false;
        } catch (error) {
            console.error("Erreur de connexion:", error);
            return false;
        }
    };

    // --- Connexion Office 365
    const loginWithO365 = async () => {
        try {
            const useRedirect = shouldUseRedirect();
            console.log(`🔐 Connexion O365: ${useRedirect ? 'REDIRECT' : 'POPUP'}`);

            if (useRedirect) {
                await instance.loginRedirect(loginRequest);
            } else {
                try {
                    const authResponse = await instance.loginPopup(loginRequest);
                    await handleSuccessfulAuth(authResponse);
                    return true;
                } catch (popupError) {
                    if (popupError.errorCode === 'popup_window_error' ||
                        popupError.errorCode === 'empty_window_error') {
                        console.warn('⚠️ Popup bloqué, fallback redirect');
                        await instance.loginRedirect(loginRequest);
                    } else {
                        throw popupError;
                    }
                }
            }
        } catch (error) {
            console.error('❌ Erreur login O365:', error);
            throw error;
        }
    };

    // --- Déconnexion
    const logout = async () => {
        try {
            const useRedirect = shouldUseRedirect();

            if (accounts.length > 0) {
                if (useRedirect) {
                    await instance.logoutRedirect({
                        account: accounts[0],
                        postLogoutRedirectUri: window.location.origin
                    });
                } else {
                    await instance.logoutPopup({
                        account: accounts[0],
                        postLogoutRedirectUri: window.location.origin
                    });
                }
            }
        } catch (error) {
            console.error('Erreur déconnexion:', error);
        } finally {
            setUser(null);
            setUserGroups([]);
            setIsAuthorized(false);
        }
    };

    // --- Obtenir token API
    const getAccessToken = async () => {
        try {
            if (accounts.length === 0) {
                throw new Error('Aucun compte connecté');
            }

            const response = await instance.acquireTokenSilent({
                ...loginRequest,
                account: accounts[0]
            });

            return response.accessToken;
        } catch (error) {
            console.error('Erreur obtention token:', error);

            // Tenter une interaction si nécessaire
            if (error.name === 'InteractionRequiredAuthError') {
                try {
                    const response = await instance.acquireTokenPopup({
                        ...loginRequest,
                        account: accounts[0]
                    });
                    return response.accessToken;
                } catch (popupError) {
                    console.error('Erreur popup token:', popupError);
                }
            }
            return null;
        }
    };

    const value = {
        user,
        userGroups,
        isAuthorized,
        login,
        loginWithO365,
        logout,
        isLoading,
        getAccessToken
    };

    return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
};

export default AuthContext;