import { useEffect, useState } from "react";
import { useNavigate, useSearchParams, Link } from "react-router-dom";
import { useAuth } from "../context/AuthContext";
import "../scss/pages.scss";

export default function AuthCallback() {
  const [searchParams] = useSearchParams();
  const { loginWithOAuth } = useAuth();
  const navigate = useNavigate();
  const [error, setError] = useState(null);

  useEffect(() => {
    const token = searchParams.get("token");

    if (!token) {
      setError("Token manquant dans l'URL.");
      return;
    }

    loginWithOAuth(token)
      .then(() => navigate("/", { replace: true }))
      .catch((err) => setError(err.message || "Erreur de connexion."));
  }, []);

  if (error) {
    return (
      <section>
        <div className="containererror">
          <h1>Erreur de connexion</h1>
          <p className="message">{error}</p>
          <Link className="btn-return" to="/login">
            Retour au login
          </Link>
        </div>
      </section>
    );
  }

  return (
    <section>
      <div className="containererror">
        <p className="message">Connexion en cours...</p>
      </div>
    </section>
  );
}
