import { Alert, CircularProgress } from "@mui/material";
import React, { useEffect, useRef } from "react";
import { useLocation } from "react-router-dom";
import { AuthApi, CheckResetTokenResponse } from "../../api/AuthApi";

export function ResetPasswordRoute(): React.ReactElement {
  const [error, setError] = React.useState<string | null>(null);

  const { hash } = useLocation();
  const token = hash.substring(1);

  const info = React.useState<null | CheckResetTokenResponse>(null);
  const checkedToken = useRef<null | string>(null);

  useEffect(() => {
    (async () => {
      if (token === checkedToken.current) return;
      checkedToken.current = token;

      try {
        setError(null);
        await AuthApi.CheckResetPasswordToken(token);
      } catch (e) {
        console.error(e);
        setError(
          "Echec de validation du jeton de réinitialisation de mot de passe!"
        );
      }
    })();
  });

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

  if (info === null)
    return (
      <>
        <CircularProgress />
      </>
    );

  return <ResetPasswordForm token={token} info={info as any} />;
}

function ResetPasswordForm(p: {
  token: string;
  info: CheckResetTokenResponse;
}): React.ReactElement {
  return <p>TODO</p>;
}
