import {
  Button,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  Typography,
} from "@mui/material";
import { useNavigate } from "react-router-dom";
import { APITokenURL, CreatedAPIToken } from "../api/TokensApi";
import { CopyToClipboard } from "../widgets/CopyToClipboard";
import { InlineCode } from "../widgets/InlineCode";

export function CreatedTokenDialog(p: {
  createdToken: CreatedAPIToken;
}): React.ReactElement {
  const navigate = useNavigate();

  const close = () => {
    navigate(APITokenURL(p.createdToken.token));
  };
  return (
    <Dialog open>
      <DialogTitle>Token successfully created</DialogTitle>
      <DialogContent>
        <Typography>
          Your token was successfully created. You need now to copy the private
          key, as it will be technically impossible to recover it after closing
          this dialog.
        </Typography>

        <InfoBlock label="Token ID" value={p.createdToken.token.id} />
        <InfoBlock label="Key algorithm" value={p.createdToken.priv_key.alg} />
        <InfoBlock label="Private key" value={p.createdToken.priv_key.priv} />
      </DialogContent>
      <DialogActions>
        <Button onClick={close} color="error">
          I copied the key, close this dialog
        </Button>
      </DialogActions>
    </Dialog>
  );
}

function InfoBlock(
  p: React.PropsWithChildren<{ label: string; value: string }>
): React.ReactElement {
  return (
    <div
      style={{ display: "flex", flexDirection: "column", margin: "20px 10px" }}
    >
      <Typography variant="overline">{p.label}</Typography>
      <CopyToClipboard content={p.value}>
        <InlineCode>{p.value}</InlineCode>
      </CopyToClipboard>
    </div>
  );
}