import { Button } from "@mui/material";
import React from "react";
import { useNavigate, useParams } from "react-router-dom";
import { APIToken, APITokenURL, TokensApi } from "../api/TokensApi";
import { AsyncWidget } from "../widgets/AsyncWidget";
import { VirtWebRouteContainer } from "../widgets/VirtWebRouteContainer";
import {
  APITokenDetails,
  TokenWidgetStatus,
} from "../widgets/tokens/APITokenDetails";

export function ViewApiTokenRoute() {
  const { id } = useParams();

  const [token, setToken] = React.useState<APIToken | undefined>();

  const load = async () => {
    setToken(await TokensApi.GetSingle(id!));
  };

  return (
    <AsyncWidget
      loadKey={id}
      ready={token !== undefined}
      errMsg="Failed to fetch API token information!"
      load={load}
      build={() => <ViewAPITokenRouteInner token={token!} />}
    />
  );
}

function ViewAPITokenRouteInner(p: { token: APIToken }): React.ReactElement {
  const navigate = useNavigate();

  return (
    <VirtWebRouteContainer
      label={`API token ${p.token.name}`}
      actions={
        <span style={{ display: "flex", alignItems: "center" }}>
          <Button
            variant="contained"
            style={{ marginLeft: "15px" }}
            onClick={() => navigate(APITokenURL(p.token, true))}
          >
            Edit
          </Button>
        </span>
      }
    >
      <APITokenDetails token={p.token} status={TokenWidgetStatus.Read} />
    </VirtWebRouteContainer>
  );
}
