import { AuthApi } from "../api/AuthApi";
import { AsyncWidget } from "../widgets/AsyncWidget";

export function AuthRouteWidget(): React.ReactElement {
  const params = new URL(document.location.toString()).searchParams;
  const code = params.get("code");
  const state = params.get("state");

  // Initiate OpenID login
  if (!code || !state) return <InitOpenIDAuth />;

  // Finish OpenID login
  return <FinishOpenIDAuth code={code} state={state} />;
}

function InitOpenIDAuth() {
  const load = async () => {
    const res = await AuthApi.StartOpenIDLogin();
    window.location.href = res.url;
  };

  return (
    <AsyncWidget
      loadingMessage="Preparing OpenID authentication"
      errMsg="Failed to initiate OpenID authentication!"
      load={load}
      loadKey={1}
      build={() => <>ready for auth</>}
    />
  );
}

function FinishOpenIDAuth(p: { code: string; state: string }) {
  const load = async () => {
    await AuthApi.FinishOpenIDLogin(p.code, p.state);
  };
  return (
    <AsyncWidget
      loadingMessage="Finishing authentication..."
      errMsg="Failed to finish OpenID authentication!"
      loadKey={1}
      load={load}
      build={() => <>Auth successfully finished. App should restart now.</>}
    />
  );
}
