import PlayArrowIcon from "@mui/icons-material/PlayArrow";
import StopIcon from "@mui/icons-material/Stop";
import { CircularProgress, Typography } from "@mui/material";
import React from "react";
import {
  NetworkApi,
  NetworkInfo,
  NetworkStatus as NetworkState,
} from "../../api/NetworksApi";
import { useSnackbar } from "../../hooks/providers/SnackbarProvider";
import { StateActionButton } from "../StateActionButton";

export function NetworkStatusWidget(p: {
  net: NetworkInfo;
  onChange?: (s: NetworkState) => void;
}): React.ReactElement {
  const snackbar = useSnackbar();

  const [state, setState] = React.useState<undefined | NetworkState>();

  const refresh = async () => {
    try {
      const s = await NetworkApi.GetState(p.net);
      if (s !== state) p.onChange?.(s);
      setState(s);
    } catch (e) {
      console.error(e);
      snackbar("Failed to refresh network status!");
    }
  };

  const changedAction = () => setState(undefined);

  React.useEffect(() => {
    refresh();
    const i = setInterval(() => refresh(), 3000);

    return () => clearInterval(i);
  });

  if (state === undefined)
    return (
      <>
        <CircularProgress size={"1rem"} />
      </>
    );

  return (
    <div style={{ display: "inline-flex" }}>
      <Typography>{state}</Typography>

      {/* Start Network */}
      <StateActionButton
        currState={state}
        cond={["Stopped"]}
        icon={<PlayArrowIcon />}
        tooltip="Start the Network"
        performAction={() => NetworkApi.Start(p.net)}
        onExecuted={changedAction}
      />

      {/* Stop network */}
      <StateActionButton
        currState={state}
        cond={["Started"]}
        icon={<StopIcon />}
        tooltip="Stop the network"
        confirmMessage="Do you really want to kill stop this network?"
        performAction={() => NetworkApi.Stop(p.net)}
        onExecuted={changedAction}
      />
    </div>
  );
}
