import { Button, Typography } from "@mui/material";
import { Link, useLocation, useNavigate } from "react-router-dom";
import { useAlert } from "../widgets/AlertDialogProvider";
import { useConfirm } from "../widgets/ConfirmDialogProvider";
import { DeleteAccountTokenInfo, UserApi } from "../api/UserApi";
import React from "react";
import { AsyncWidget } from "../widgets/AsyncWidget";
import { AuthApi } from "../api/AuthApi";

export function DeleteAccountRoute(): React.ReactElement {
  const alert = useAlert();
  const confirm = useConfirm();
  const navigate = useNavigate();

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

  const [info, setInfo] = React.useState<DeleteAccountTokenInfo>();

  const checkToken = async () => {
    setInfo(await UserApi.CheckDeleteAccountToken(token));
  };

  const doDelete = async () => {
    try {
      if (
        !(await confirm.confirm(
          "Voulez-vous vraiment supprimer votre compte ?",
          undefined,
          "Supprimer mon compte"
        ))
      )
        return;

      await UserApi.DeleteAccount(token);
      AuthApi.RemoveAuthToken();

      await alert.alert("Votre compte a été supprimé avec succès !");

      navigate("/");
    } catch (e) {
      console.error(e);
      alert.alert("Echec de la suppression du compte !");
    }
  };

  return (
    <AsyncWidget
      errMsg="Echec de la validation du jeton de suppression de compte !"
      load={checkToken}
      loadKey={token}
      build={() => (
        <div
          style={{
            height: "100vh",
            backgroundColor: "#b23c17",
            color: "white",
            display: "flex",
            justifyContent: "center",
            alignItems: "center",
            flexDirection: "column",
          }}
        >
          <Typography variant="h3">Suppression de compte</Typography>
          <p>{info?.email}</p>
          <p>
            Voulez-vous vraiment supprimer votre compte ? Cette opération est
            irréversible !
          </p>
          <Button onClick={doDelete} color="inherit">
            Supprimer mon compte
          </Button>
          <Link to="/" style={{ color: "inherit", textDecoration: "none" }}>
            <Button color="inherit">Annuler</Button>
          </Link>
        </div>
      )}
    />
  );
}
