import {
  Dialog,
  DialogTitle,
  DialogContent,
  DialogContentText,
  TextField,
  DialogActions,
  Button,
} from "@mui/material";
import { MatrixLinkApi } from "../api/MatrixLinkApi";
import { useAlert } from "../hooks/contexts_provider/AlertDialogProvider";
import { useLoadingMessage } from "../hooks/contexts_provider/LoadingMessageProvider";
import { useSnackbar } from "../hooks/contexts_provider/SnackbarProvider";
import React from "react";
import { useUserInfo } from "../widgets/dashboard/BaseAuthenticatedPage";

export function SetRecoveryKeyDialog(p: {
  open: boolean;
  onClose: () => void;
}): React.ReactElement {
  const alert = useAlert();
  const snackbar = useSnackbar();
  const loadingMessage = useLoadingMessage();

  const user = useUserInfo();

  const [newKey, setNewKey] = React.useState("");

  const handleSubmitKey = async () => {
    try {
      loadingMessage.show("Updating recovery key...");

      await MatrixLinkApi.SetRecoveryKey(newKey);
      setNewKey("");
      p.onClose();

      snackbar("Recovery key successfully updated!");
      user.reloadUserInfo();
    } catch (e) {
      console.error(`Failed to set new recovery key! ${e}`);
      alert(`Failed to set new recovery key! ${e}`);
    } finally {
      loadingMessage.hide();
    }
  };

  return (
    <Dialog open={p.open} onClose={p.onClose}>
      <DialogTitle>Set new recovery key</DialogTitle>
      <DialogContent>
        <DialogContentText>
          Enter below you recovery key to verify this session and gain access to
          old messages.
        </DialogContentText>
        <TextField
          label="Recovery key"
          type="text"
          variant="standard"
          autoComplete="off"
          value={newKey}
          onChange={(e) => setNewKey(e.target.value)}
          fullWidth
        />
      </DialogContent>
      <DialogActions>
        <Button onClick={p.onClose}>Cancel</Button>
        <Button onClick={handleSubmitKey} disabled={newKey === ""} autoFocus>
          Submit
        </Button>
      </DialogActions>
    </Dialog>
  );
}
