import { Alert, Box, Button, CircularProgress } from "@mui/material";
import React from "react";
import { useNavigate, useSearchParams } from "react-router";
import { MatrixLinkApi } from "../api/MatrixLinkApi";
import { useUserInfo } from "../widgets/dashboard/BaseAuthenticatedPage";
import { RouterLink } from "../widgets/RouterLink";
import { useSnackbar } from "../hooks/contexts_provider/SnackbarProvider";

export function MatrixAuthCallback(): React.ReactElement {
  const navigate = useNavigate();
  const snackbar = useSnackbar();

  const info = useUserInfo();

  const [error, setError] = React.useState<null | string>(null);

  const [searchParams] = useSearchParams();
  const code = searchParams.get("code");
  const state = searchParams.get("state");

  const count = React.useRef("");

  React.useEffect(() => {
    const load = async () => {
      try {
        if (count.current === code) {
          return;
        }
        count.current = code!;

        await MatrixLinkApi.FinishAuth(code!, state!);

        snackbar("Successfully linked to Matrix account!");
        navigate("/matrix_link");
      } catch (e) {
        console.error(e);
        setError(String(e));
      } finally {
        info.reloadUserInfo();
      }
    };

    load();
  }, [code, state]);

  if (error)
    return (
      <Box
        component="div"
        sx={{
          display: "flex",
          justifyContent: "center",
          alignItems: "center",
          height: "100%",
          flex: "1",
          flexDirection: "column",
        }}
      >
        <Alert
          variant="outlined"
          severity="error"
          style={{ margin: "0px 15px 15px 15px" }}
        >
          Failed to finalize Matrix authentication!
          <br />
          <br />
          {error}
        </Alert>

        <Button>
          <RouterLink to="/matrix_link">Go back</RouterLink>
        </Button>
      </Box>
    );

  return (
    <div style={{ textAlign: "center" }}>
      <CircularProgress />
    </div>
  );
}
