import React, { useEffect, useState } from 'react';
import { Navigate, useNavigate } from 'react-router-dom';
import { useAuth } from '../context/AuthContext';
import { api } from '../lib/api';
import { toast } from 'sonner';
import { Lock, User2, KeyRound, ArrowLeft } from 'lucide-react';

const LOGO_GP = "/logo-gp.png";

export default function Login() {
    const { user, login } = useAuth();
    const navigate = useNavigate();
    const [username, setUsername] = useState('');
    const [password, setPassword] = useState('');
    const [loading, setLoading] = useState(false);
    const [legacyMode, setLegacyMode] = useState(false);
    const [legacyAvailable, setLegacyAvailable] = useState(false);

    useEffect(() => {
        api.get('/settings/public')
            .then((r) => setLegacyAvailable(!!r.data?.legacy_login_enabled))
            .catch(() => setLegacyAvailable(false));
    }, []);

    if (user) {
        if (user.must_change_password) return <Navigate to="/change-password" replace />;
        return <Navigate to="/" replace />;
    }

    const handlePwdChange = (e) => {
        if (legacyMode) {
            setPassword(e.target.value);
        } else {
            const v = e.target.value.replace(/\D/g, '').slice(0, 6);
            setPassword(v);
        }
    };

    const switchToLegacy = () => { setLegacyMode(true); setPassword(''); };
    const switchToCode = () => { setLegacyMode(false); setPassword(''); };

    const handleSubmit = async (e) => {
        e.preventDefault();
        if (!username.trim()) { toast.error('Identifiant requis'); return; }
        if (legacyMode) {
            if (!password) { toast.error('Mot de passe requis'); return; }
        } else if (!/^\d{6}$/.test(password)) {
            toast.error('Le code doit contenir 6 chiffres'); return;
        }
        try {
            if ('Notification' in window && Notification.permission === 'default') {
                Notification.requestPermission().catch(() => {});
            }
        } catch (_) {}
        setLoading(true);
        try {
            const u = await login(username.trim().toLowerCase(), password, legacyMode);
            if (legacyMode) toast.success('Connexion réussie — choisis ton nouveau code à 6 chiffres');
            else toast.success('Connexion réussie');
            navigate(u.must_change_password ? '/change-password' : '/');
        } catch (err) {
            toast.error(err?.response?.data?.detail || 'Identifiants invalides');
        } finally {
            setLoading(false);
        }
    };

    return (
        <div className="min-h-screen relative overflow-hidden bg-white flex items-center justify-center p-4 sm:p-6">
            {/* Subtle radial glows only, no grid */}
            <div
                aria-hidden="true"
                className="absolute inset-0"
                style={{
                    background:
                        'radial-gradient(900px 500px at 12% 15%, rgba(37, 99, 235, 0.10) 0%, transparent 60%),' +
                        ' radial-gradient(800px 500px at 88% 85%, rgba(249, 115, 22, 0.10) 0%, transparent 60%),' +
                        ' #ffffff',
                }}
            />

            {/* Logo flottant au-dessus du carré */}
            <div className="relative z-10 w-full max-w-md flex flex-col items-center">
                <div
                    className="relative z-10 mb-[-4.5rem] sm:mb-[-5rem]"
                    data-testid="login-logo-wrapper"
                >
                    <div className="absolute inset-0 blur-3xl opacity-50 rounded-full bg-gradient-to-br from-blue-400/40 via-orange-400/30 to-transparent" />
                    <img
                        src={LOGO_GP}
                        alt="Gestion Palettes"
                        data-testid="login-logo"
                        className="relative h-60 w-60 sm:h-72 sm:w-72 object-contain drop-shadow-[0_10px_30px_rgba(15,23,42,0.18)]"
                    />
                </div>

                {/* Carré central — soft card on white */}
                <div
                    data-testid="login-card"
                    className="relative w-full rounded-2xl border border-slate-200 bg-white shadow-[0_20px_60px_-15px_rgba(15,23,42,0.18)] px-6 sm:px-8 pt-28 sm:pt-32 pb-8"
                >
                    <div className="text-center">
                        <p className="text-[11px] font-bold uppercase tracking-[0.3em] text-orange-500">
                            {legacyMode ? 'Migration code' : 'Connexion'}
                        </p>
                        <h1 className="mt-2 font-heading text-3xl sm:text-4xl font-black tracking-tight text-slate-900">
                            Gestion Palettes
                        </h1>
                        <p className="mt-2 text-sm text-slate-500 max-w-sm mx-auto">
                            {legacyMode
                                ? 'Utilise ton ancien mot de passe. Tu choisiras un nouveau code à 6 chiffres juste après.'
                                : 'Identifiant + code à 6 chiffres'}
                        </p>
                    </div>

                    <form onSubmit={handleSubmit} className="mt-7 space-y-4" data-testid="login-form">
                        <div>
                            <label className="text-[11px] font-bold uppercase tracking-[0.2em] text-slate-700">
                                Identifiant
                            </label>
                            <div className="mt-1.5 relative">
                                <User2 className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400" />
                                <input
                                    data-testid="username-input"
                                    value={username}
                                    onChange={(e) => setUsername(e.target.value)}
                                    type="text"
                                    placeholder="prenom.x"
                                    autoComplete="username"
                                    autoCapitalize="none"
                                    autoCorrect="off"
                                    spellCheck="false"
                                    className="w-full h-12 rounded-lg border border-slate-300 bg-white pl-10 pr-3 text-base font-medium text-slate-900 placeholder:text-slate-400 focus:border-orange-500 focus:outline-none focus:ring-2 focus:ring-orange-500/20 transition"
                                    autoFocus
                                />
                            </div>
                        </div>

                        <div>
                            <label className="text-[11px] font-bold uppercase tracking-[0.2em] text-slate-700">
                                {legacyMode ? 'Ancien mot de passe' : 'Code à 6 chiffres'}
                            </label>
                            <div className="mt-1.5 relative">
                                <Lock className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400" />
                                {legacyMode ? (
                                    <input
                                        data-testid="password-input-legacy"
                                        value={password}
                                        onChange={handlePwdChange}
                                        type="password"
                                        placeholder="Ton ancien mot de passe"
                                        autoComplete="current-password"
                                        className="w-full h-12 rounded-lg border border-slate-300 bg-white pl-10 pr-3 text-base font-medium text-slate-900 placeholder:text-slate-400 focus:border-orange-500 focus:outline-none focus:ring-2 focus:ring-orange-500/20 transition"
                                    />
                                ) : (
                                    <input
                                        data-testid="password-input"
                                        value={password}
                                        onChange={handlePwdChange}
                                        type="password"
                                        inputMode="numeric"
                                        pattern="\d{6}"
                                        maxLength={6}
                                        placeholder="••••••"
                                        autoComplete="current-password"
                                        className="w-full h-12 rounded-lg border border-slate-300 bg-white pl-10 pr-3 text-2xl font-bold tracking-[0.5em] text-slate-900 placeholder:text-slate-400 placeholder:tracking-[0.5em] focus:border-orange-500 focus:outline-none focus:ring-2 focus:ring-orange-500/20 transition text-center"
                                    />
                                )}
                            </div>
                        </div>

                        <button
                            data-testid="login-submit-btn"
                            type="submit"
                            disabled={loading}
                            className="w-full h-12 rounded-lg bg-gradient-to-r from-orange-500 to-orange-600 text-white font-heading font-black tracking-wide hover:from-orange-400 hover:to-orange-500 transition-all disabled:opacity-60 active:scale-[0.99] shadow-lg shadow-orange-500/30"
                        >
                            {loading ? 'Connexion…' : 'Se connecter'}
                        </button>
                    </form>

                    {legacyAvailable && !legacyMode && (
                        <button
                            type="button"
                            data-testid="legacy-mode-toggle"
                            onClick={switchToLegacy}
                            className="mt-4 w-full inline-flex items-center justify-center gap-2 rounded-lg border border-slate-200 bg-white px-4 h-11 text-sm font-semibold text-slate-700 hover:border-orange-500 hover:text-orange-600 transition-all"
                        >
                            <KeyRound className="h-4 w-4" />
                            Connexion avec ancien mot de passe
                        </button>
                    )}
                    {legacyMode && (
                        <button
                            type="button"
                            data-testid="legacy-mode-back"
                            onClick={switchToCode}
                            className="mt-4 w-full inline-flex items-center justify-center gap-2 rounded-lg border border-slate-200 bg-white px-4 h-11 text-sm font-semibold text-slate-700 hover:border-orange-500 hover:text-orange-600 transition-all"
                        >
                            <ArrowLeft className="h-4 w-4" />
                            Retour à la connexion par code
                        </button>
                    )}

                    <p className="mt-6 text-center text-[11px] text-slate-400">
                        Pas de compte ? Contacte le bureau.
                    </p>
                </div>

                <p className="mt-6 text-[10px] uppercase tracking-[0.3em] text-slate-400">
                    gp-eff.fr · Gestion Palettes
                </p>
            </div>
        </div>
    );
}
