﻿import React, { useState } from 'react';
import { useAuth } from '../context/AuthContext';
import { useNavigate } from 'react-router-dom';
import { Building2, 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('');

    const navigate = useNavigate();
    const { login, loginWithO365 } = 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 {
            const success = await loginWithO365();

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

            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-4">
                            <img
                                src="/assets/GA.svg"
                                alt="GTA Logo"
                                className="h-36 lg:h-40 w-auto mx-auto"
                            />
                            <p className="text-lg lg:text-xl font-semibold mb-6" style={{ color: '#7e5aa2' }}>
                                GESTION DES TEMPS ET DES ACTIVITÉS
                            </p>
                        </div>

                        {/* Bouton Office 365 */}
                        <div className="mb-4">
                            <button
                                data-testid="o365-login-btn"
                                onClick={handleO365Login}
                                disabled={isLoading}
                                type="button"
                                className="w-full bg-cyan-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="flex items-center my-4">
                            <div className="flex-1 h-px bg-gray-200" />
                            <span className="px-3 text-xs text-gray-500">ou connexion locale</span>
                            <div className="flex-1 h-px bg-gray-200" />
                        </div>

                        {/* Formulaire local email/mot de passe */}
                        <form onSubmit={handleSubmit} className="space-y-4">
                            <div>
                                <label className="block text-sm font-medium text-gray-700 mb-1">
                                    Email professionnel
                                </label>
                                <input
                                    type="email"
                                    value={email}
                                    onChange={(e) => setEmail(e.target.value)}
                                    required
                                    className="w-full px-3 py-2 border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500"
                                    placeholder="prenom.nom@ensup.fr"
                                />
                            </div>

                            <div>
                                <label className="block text-sm font-medium text-gray-700 mb-1">
                                    Mot de passe
                                </label>
                                <div className="relative">
                                    <input
                                        type={showPassword ? 'text' : 'password'}
                                        value={password}
                                        onChange={(e) => setPassword(e.target.value)}
                                        required
                                        className="w-full px-3 py-2 border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500 pr-10"
                                        placeholder="••••••••"
                                    />
                                    <button
                                        type="button"
                                        onClick={() => setShowPassword(!showPassword)}
                                        className="absolute inset-y-0 right-0 px-3 text-xs text-gray-500"
                                    >
                                        {showPassword ? 'Masquer' : 'Afficher'}
                                    </button>
                                </div>
                            </div>

                            <button
                                type="submit"
                                disabled={isLoading && authMethod === 'local'}
                                className="w-full bg-indigo-600 text-white py-2.5 rounded-lg text-sm font-medium hover:bg-indigo-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                            >
                                {isLoading && authMethod === 'local'
                                    ? 'Connexion...'
                                    : 'Se connecter'}
                            </button>
                        </form>

                        {/* Message d'erreur */}
                        {error && (
                            <div className="p-3 bg-red-50 border border-red-200 rounded-lg mt-4">
                                <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>
                        )}
                    </div>
                </div>
            </div>
        </div>
    );
};

export default Login;
