import { Alert, Box, Button, CircularProgress } from "@mui/material";
import React from "react";
import { AuthApi } from "../../api/AuthApi";
import { ServerApi } from "../../api/ServerApi";
import { AppIcon } from "../../icons/AppIcon";
import openid from "../../icons/openid.svg";

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 (
      <div style={{ textAlign: "center" }}>
        <CircularProgress />
      </div>
    );

  return (
    <>
      {error && (
        <Alert style={{ width: "100%" }} severity="error">
          {error}
        </Alert>
      )}
      <Box sx={{ display: "flex", flexDirection: "column", gap: 2 }}>
        <Button
          fullWidth
          variant="outlined"
          onClick={authWithOpenID}
          startIcon={<AppIcon src={openid} />}
        >
          Sign in with {ServerApi.Config.oidc_provider_name}
        </Button>
      </Box>
    </>
  );
}
