import React, { useState } from 'react';
import { useAuth } from '../context/AuthContext';
import { useNavigate } from 'react-router-dom';
import { Building2, Mail, Lock, Eye, EyeOff, AlertTriangle } from 'lucide-react';

const Login = () => {
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    const [showPassword, setShowPassword] = useState(false);
    const [isLoading, setIsLoading] = useState(false);
    const [error, setError] = useState('');
    const [authMethod, setAuthMethod] = useState(''); // Pour tracker la méthode d'auth utilisée

    const navigate = useNavigate();
    const { login, loginWithO365, isAuthorized } = useAuth();

    const handleSubmit = async (e) => {
        e.preventDefault();
        setIsLoading(true);
        setError('');
        setAuthMethod('local');

        try {
            const success = await login(email, password);
            if (success) {
                navigate('/dashboard');
            } else {
                setError('Identifiants incorrects. Veuillez réessayer.');
            }
        } catch (error) {
            setError(error.message || 'Erreur lors de la connexion');
        }

        setIsLoading(false);
    };

    const handleO365Login = async () => {
        setIsLoading(true);
        setError('');
        setAuthMethod('o365');

        try {
            // Étape 1 : Login O365
            const success = await loginWithO365();

            if (!success) {
                setError("Erreur lors de la connexion Office 365");
                setIsLoading(false);
                return;
            }

            // Étape 2 : Récupération du token d’authentification (si ton context le fournit)
            const token = localStorage.getItem("o365_token");
            // ⚠️ Ici j’imagine que tu stockes ton token quelque part (dans ton AuthContext ou localStorage).
            // Adapte selon ton implémentation de loginWithO365

            // Étape 3 : Appel de ton API PHP
            const response = await fetch("http://localhost/GTA/project/public/php/initial-sync.php", {
                method: "POST",
                headers: {
                    "Authorization": `Bearer ${token}`,
                    "Content-Type": "application/json",
                },
            });

            const data = await response.json();
            console.log("Résultat syncGroups :", data);

            if (!data.success) {
                setError("Erreur de synchronisation des groupes : " + data.message);
                setIsLoading(false);
                return;
            }

            // Étape 4 : Redirection vers le dashboard
            navigate('/dashboard');

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

            if (error.message?.includes('non autorisé') || error.message?.includes('Accès refusé')) {
                setError('Accès refusé : Vous devez être membre d\'un groupe autorisé dans votre organisation.');
            } else if (error.message?.includes('AADSTS')) {
                setError('Erreur d\'authentification Azure AD. Contactez votre administrateur.');
            } else {
                setError(error.message || "Erreur lors de la connexion Office 365");
            }
        }

        setIsLoading(false);
    };


    return (
        <div className="min-h-screen bg-gradient-to-br from-blue-50 to-indigo-100 flex flex-col lg:flex-row">
            {/* Image côté gauche */}
            <div className="h-32 lg:h-auto lg:flex lg:w-1/2 bg-cover bg-center"
                style={{ backgroundImage: "url('/assets/ImageEnsup.png')" }}>
                <div className="w-full bg-black bg-opacity-40 flex items-center justify-center p-4">
                </div>
            </div>

            {/* Formulaire côté droit */}
            <div className="flex-1 lg:w-1/2 flex items-center justify-center p-4 lg:p-8">
                <div className="max-w-md w-full">
                    <div className="bg-white rounded-2xl shadow-xl p-6 lg:p-8">
                        {/* Logo */}
                        <div className="text-center mb-6 lg:mb-8">
                            <div className="w-12 h-12 lg:w-16 lg:h-16 bg-blue-600 rounded-2xl flex items-center justify-center mx-auto mb-4">
                                <Building2 className="w-6 h-6 lg:w-8 lg:h-8 text-white" />
                            </div>
                            <h1 className="text-xl lg:text-2xl font-bold text-gray-900">GTA</h1>
                            <p className="text-sm lg:text-base text-gray-600">Gestion de congés</p>
                        </div>

                        {/* Connexion Office 365 prioritaire */}
                        <div className="mb-6">
                            <button
                                onClick={handleO365Login}
                                disabled={isLoading}
                                type="button"
                                className="w-full bg-blue-600 text-white py-3 rounded-lg font-medium hover:bg-blue-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center space-x-2"
                            >
                                {isLoading && authMethod === 'o365' ? (
                                    <span>Connexion Office 365...</span>
                                ) : (
                                    <>
                                        <svg className="w-5 h-5" viewBox="0 0 21 21" fill="currentColor">
                                            <path d="M10.5 0L0 7v7l10.5 7L21 14V7L10.5 0zM3.5 8.5L10.5 3l7 5.5v5L10.5 19l-7-5.5v-5z" />
                                        </svg>
                                        <span>Se connecter avec Office 365</span>
                                    </>
                                )}
                            </button>
                        </div>

                        {/* Séparateur */}
                        <div className="relative mb-6">
                            <div className="absolute inset-0 flex items-center">
                                <div className="w-full border-t border-gray-300"></div>
                            </div>
                            <div className="relative flex justify-center text-sm">
                                <span className="px-2 bg-white text-gray-500">ou</span>
                            </div>
                        </div>

                        {/* Formulaire classique */}
                        <form onSubmit={handleSubmit} className="space-y-4 lg:space-y-6">
                            <div>
                                <label htmlFor="email" className="block text-sm lg:text-base font-medium text-gray-700 mb-2">
                                    Email
                                </label>
                                <div className="relative">
                                    <Mail className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4 lg:w-5 lg:h-5" />
                                    <input
                                        id="email"
                                        type="email"
                                        value={email}
                                        onChange={(e) => setEmail(e.target.value)}
                                        className="w-full pl-9 lg:pl-10 pr-4 py-2 lg:py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm lg:text-base"
                                        placeholder="votre.email@entreprise.com"
                                        required
                                        disabled={isLoading}
                                    />
                                </div>
                            </div>

                            <div>
                                <label htmlFor="password" className="block text-sm lg:text-base font-medium text-gray-700 mb-2">
                                    Mot de passe
                                </label>
                                <div className="relative">
                                    <Lock className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4 lg:w-5 lg:h-5" />
                                    <input
                                        id="password"
                                        type={showPassword ? "text" : "password"}
                                        value={password}
                                        onChange={(e) => setPassword(e.target.value)}
                                        className="w-full pl-9 lg:pl-10 pr-10 lg:pr-12 py-2 lg:py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent text-sm lg:text-base"
                                        placeholder="••••••••"
                                        required
                                        disabled={isLoading}
                                    />
                                    <button
                                        type="button"
                                        onClick={() => setShowPassword(!showPassword)}
                                        className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 hover:text-gray-900 disabled:opacity-50"
                                        disabled={isLoading}
                                        title={showPassword ? "Masquer le mot de passe" : "Afficher le mot de passe"}
                                    >
                                        {showPassword ? <EyeOff className="w-5 h-5" /> : <Eye className="w-5 h-5" />}
                                    </button>
                                </div>
                            </div>

                            {/* Affichage des erreurs */}
                            {error && (
                                <div className="p-3 bg-red-50 border border-red-200 rounded-lg">
                                    <div className="flex items-start space-x-2">
                                        <AlertTriangle className="w-5 h-5 text-red-500 flex-shrink-0 mt-0.5" />
                                        <div className="flex-1">
                                            <p className="text-red-700 text-sm font-medium">
                                                {error.includes('Accès refusé') ? 'Accès refusé' : 'Erreur de connexion'}
                                            </p>
                                            <p className="text-red-600 text-xs mt-1">{error}</p>
                                            {error.includes('groupe autorisé') && (
                                                <p className="text-red-600 text-xs mt-2">
                                                    Contactez votre administrateur pour être ajouté aux groupes appropriés.
                                                </p>
                                            )}
                                        </div>
                                    </div>
                                </div>
                            )}

                            <button
                                type="submit"
                                disabled={isLoading}
                                className="w-full bg-gray-600 text-white py-2 lg:py-3 px-4 rounded-lg font-medium hover:bg-gray-700 focus:ring-2 focus:ring-gray-500 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed transition-colors text-sm lg:text-base"
                            >
                                {isLoading && authMethod === 'local' ? 'Connexion...' : 'Connexion locale'}
                            </button>
                        </form>

                        {/* Info sur l'authentification */}
                        <div className="mt-6 text-center">
                            <p className="text-xs text-gray-500">
                                Utilisez votre compte Office 365 pour une connexion sécurisée
                            </p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    );
};

export default Login;