import { Button, CircularProgress } from "@mui/material";
import { useEffect, useRef, useState } from "react";
import { Link, useSearchParams } from "react-router-dom";
import { AuthApi } from "../../api/AuthApi";
import { useSetAtom } from "jotai";

/**
 * OpenID login callback route
 */
export function OIDCCbRoute(): React.ReactElement {
  const setAuth = useSetAtom(AuthApi.authStatus);

  const [error, setError] = useState(false);

  const [searchParams] = useSearchParams();
  const code = searchParams.get("code");
  const state = searchParams.get("state");

  const count = useRef("");

  useEffect(() => {
    const load = async () => {
      try {
        if (count.current === code) {
          return;
        }
        count.current = code!;

        await AuthApi.FinishOpenIDLogin(code!, state!);
        setAuth(true);
      } catch (e) {
        console.error(e);
        setError(true);
      }
    };

    load();
  }, [code, state]);

  if (error)
    return (
      <>
        <p>Echec de la finalisation de l'authentification !</p>
        <Link to={"/"}>
          <Button>Retour à l'accueil</Button>
        </Link>
      </>
    );

  return (
    <>
      <CircularProgress />
    </>
  );
}
