import React, { useEffect, useRef, useState } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { api } from '../lib/api';
import { useAuth } from '../context/AuthContext';
import { toast } from 'sonner';
import { Loader2, ShieldAlert } from 'lucide-react';

const LOGO_URL = "/logo.png";

export default function SsoLanding() {
    const [params] = useSearchParams();
    const navigate = useNavigate();
    const { setSession } = useAuth();
    const [error, setError] = useState(null);
    const exchanged = useRef(false);

    useEffect(() => {
        if (exchanged.current) return;
        exchanged.current = true;

        const token = params.get('t') || params.get('token');
        if (!token) {
            setError("Lien SSO invalide (pas de token)");
            return;
        }

        (async () => {
            try {
                const r = await api.post('/auth/sso', { token });
                setSession(r.data.token, r.data.user);
                toast.success(`Connecté en SSO`);
                navigate(r.data.user.must_change_password ? '/change-password' : '/', { replace: true });
            } catch (err) {
                const msg = err?.response?.data?.detail || 'Connexion SSO impossible';
                setError(msg);
            }
        })();
    }, [params, navigate, setSession]);

    return (
        <div className="min-h-screen flex items-center justify-center bg-[#F8FAFC] p-5">
            <div className="w-full max-w-md rounded-xl border border-slate-200 bg-white shadow-sm p-8 text-center">
                <img src={LOGO_URL} alt="My Truck" className="h-14 w-14 object-contain mx-auto mb-4" />
                {!error ? (
                    <>
                        <p className="text-xs font-bold uppercase tracking-[0.2em] text-stef">Connexion SSO</p>
                        <h1 className="mt-2 font-heading text-2xl font-black text-slate-900">Connexion en cours…</h1>
                        <p className="mt-2 text-sm text-slate-600">Validation du lien depuis GP.</p>
                        <Loader2 className="mt-6 h-6 w-6 animate-spin text-stef mx-auto" />
                    </>
                ) : (
                    <>
                        <div className="mx-auto h-12 w-12 rounded-full bg-red-50 text-red-600 flex items-center justify-center mb-3">
                            <ShieldAlert className="h-6 w-6" />
                        </div>
                        <h1 className="font-heading text-xl font-black text-slate-900">Connexion refusée</h1>
                        <p className="mt-2 text-sm text-slate-600" data-testid="sso-error">{error}</p>
                        <button
                            onClick={() => navigate('/login', { replace: true })}
                            className="mt-5 inline-flex items-center justify-center h-11 rounded-md bg-stef px-5 text-sm font-heading font-bold text-white hover:bg-stef-hover transition"
                            data-testid="sso-fallback-login"
                        >
                            Se connecter manuellement
                        </button>
                    </>
                )}
            </div>
        </div>
    );
}
