import React, { createContext, useContext, useState, useEffect } from 'react';
import * as msal from '@azure/msal-browser';

const AuthContext = createContext();

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

const msalConfig = {
    auth: {
        clientId: '4bb4cc24-bac3-427c-b02c-5d14fc67b561',
        authority: 'https://login.microsoftonline.com/9840a2a0-6ae1-4688-b03d-d2ec291be0f9',
        redirectUri: window.location.origin,
    },
};

const msalInstance = new msal.PublicClientApplication(msalConfig);

export const AuthProvider = ({ children }) => {
    const [user, setUser] = useState(null);
    const [isLoading, setIsLoading] = useState(true);

    // Initialise MSAL au montage
    useEffect(() => {
        const initializeMsal = async () => {
            try {
                await msalInstance.initialize();
            } catch (error) {
                console.error("Erreur d'initialisation MSAL:", error);
            }
        };

        initializeMsal();

        const savedUser = localStorage.getItem('user');
        if (savedUser) {
            try {
                setUser(JSON.parse(savedUser));
            } catch (error) {
                console.error("Erreur parsing utilisateur sauvegardé:", error);
                localStorage.removeItem('user');
            }
        }
        setIsLoading(false);
    }, []);

    const login = async (email, password) => {
        try {
            const possibleUrls = [
                'http://localhost/GTA/project/public/login.php',
                'http://localhost:80/GTA/project/public/login.php',
                'http://localhost/GTA/public/login.php',
                'http://localhost/public/login.php'
            ];

            let response = null;
            for (const url of possibleUrls) {
                try {
                    console.log("Test URL:", url);
                    response = await fetch(url, {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ email, mot_de_passe: password }),
                    });
                    if (response.ok) break;
                } catch {
                    continue;
                }
            }

            if (!response || !response.ok) {
                throw new Error('Aucune URL de connexion accessible');
            }

            const text = await response.text();
            let data;
            try {
                data = JSON.parse(text);
            } catch {
                console.error("Réponse non-JSON:", text.substring(0, 200));
                throw new Error("Le serveur PHP ne répond pas correctement.");
            }

            if (data.success) {
                const userData = {
                    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'
                };

                setUser(userData);
                localStorage.setItem('user', JSON.stringify(userData));
                return true;
            } else {
                console.error("Échec connexion:", data.message);
                return false;
            }
        } catch (error) {
            console.error("Erreur de connexion:", error);
            return false;
        }
    };

    const loginWithO365 = async () => {
        try {
            const loginResponse = await msalInstance.loginPopup({
                scopes: ["user.read"]
            });
            const account = loginResponse.account;
            if (account) {
                const userData = {
                    id: account.homeAccountId,
                    name: account.name,
                    email: account.username,
                    role: 'Employe',
                    service: 'Non défini',
                };
                setUser(userData);
                localStorage.setItem('user', JSON.stringify(userData));
                return true;
            }
            return false;
        } catch (error) {
            console.error('Erreur login Office 365:', error);
            return false;
        }
    };

    const logout = () => {
        setUser(null);
        localStorage.removeItem('user');
    };

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

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

export default AuthContext;
