import { Alert, CircularProgress } from "@mui/material";
import Button from "@mui/material/Button";
import * as React from "react";
import { AuthApi } from "../../api/AuthApi";
import { ServerApi } from "../../api/ServerApi";

/**
 * Login form
 */
export function LoginRoute(): React.ReactElement {
  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState<string | null>(null);

  const authWithOpenID = async () => {
    try {
      setLoading(true);

      const res = await AuthApi.StartOpenIDLogin();
      window.location.href = res.url;
    } catch (e) {
      console.error(e);
      setError("Failed to initialize OpenID login");
    }
  };

  if (loading)
    return (
      <>
        <CircularProgress />
      </>
    );

  return (
    <>
      {error && (
        <Alert style={{ width: "100%" }} severity="error">
          {error}
        </Alert>
      )}

      <div>
        <Button
          style={{ textAlign: "center", width: "100%", marginTop: "20px" }}
          onClick={() => authWithOpenID()}
        >
          Authenticate using {ServerApi.Config.oidc_provider_name}
        </Button>
      </div>
    </>
  );
}
