import { CircularProgress } from "@mui/material";
import { useEffect, useRef, useState } from "react";
import { useNavigate, useSearchParams } from "react-router-dom";
import { AuthApi } from "../../api/AuthApi";
import { useAuth } from "../../App";
import { AuthSingleMessage } from "../../widgets/AuthSingleMessage";

/**
 * OpenID login callback route
 */
export function OIDCCbRoute(): React.ReactElement {
  const auth = useAuth();
  const navigate = useNavigate();

  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!);
        navigate("/");
        auth.setSignedIn(true);
      } catch (e) {
        console.error(e);
        setError(true);
      }
    };

    load();
  });

  if (error)
    return (
      <AuthSingleMessage message="Failed to finalize OpenID authentication!" />
    );

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