import { Button } from "@mui/material";
import React from "react";
import { useNavigate, useParams } from "react-router-dom";
import {
  NetworkApi,
  NetworkInfo,
  NetworkStatus,
  NetworkURL,
} from "../api/NetworksApi";
import { AsyncWidget } from "../widgets/AsyncWidget";
import { ConfigImportExportButtons } from "../widgets/ConfigImportExportButtons";
import { VirtWebRouteContainer } from "../widgets/VirtWebRouteContainer";
import { NetworkDetails } from "../widgets/net/NetworkDetails";
import { NetworkStatusWidget } from "../widgets/net/NetworkStatusWidget";

export function ViewNetworkRoute() {
  const { uuid } = useParams();

  const [network, setNetwork] = React.useState<NetworkInfo | undefined>();

  const load = async () => {
    setNetwork(await NetworkApi.GetSingle(uuid!));
  };

  return (
    <AsyncWidget
      loadKey={uuid}
      ready={network !== undefined}
      errMsg="Failed to fetch network information!"
      load={load}
      build={() => <ViewNetworkRouteInner network={network!} />}
    />
  );
}

function ViewNetworkRouteInner(p: {
  network: NetworkInfo;
}): React.ReactElement {
  const navigate = useNavigate();

  const [netStatus, setNetStatus] = React.useState<NetworkStatus | undefined>();

  return (
    <VirtWebRouteContainer
      label={`Network ${p.network.name}`}
      actions={
        <span style={{ display: "flex", alignItems: "center" }}>
          <NetworkStatusWidget net={p.network} onChange={setNetStatus} />

          <ConfigImportExportButtons
            filename={`net-${p.network.name}.json`}
            currentConf={p.network}
          />

          {netStatus === "Stopped" && (
            <Button
              variant="contained"
              style={{ marginLeft: "15px" }}
              onClick={() => navigate(NetworkURL(p.network, true))}
            >
              Edit
            </Button>
          )}
        </span>
      }
    >
      <NetworkDetails net={p.network} editable={false} />
    </VirtWebRouteContainer>
  );
}
