import { Alert, Box, Button, CircularProgress } from "@mui/material";
import Icon from "@mdi/react";
import { mdiOpenid } from "@mdi/js";
import { ServerApi } from "../../api/ServerApi";
import React from "react";
import { AuthApi } from "../../api/AuthApi";

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={<Icon path={mdiOpenid} size={1} />}
        >
          Sign in with {ServerApi.Config.oidc_provider_name}
        </Button>
      </Box>
    </>
  );
}
