import { mdiXml } from "@mdi/js";
import Icon from "@mdi/react";
import { Button, IconButton, Tooltip } from "@mui/material";
import React from "react";
import { useNavigate, useParams } from "react-router-dom";
import { VMApi, VMInfo, VMState } from "../api/VMApi";
import { AsyncWidget } from "../widgets/AsyncWidget";
import { ConfigImportExportButtons } from "../widgets/ConfigImportExportButtons";
import { RouterLink } from "../widgets/RouterLink";
import { VirtWebRouteContainer } from "../widgets/VirtWebRouteContainer";
import { VMDetails } from "../widgets/vms/VMDetails";
import { VMStatusWidget } from "../widgets/vms/VMStatusWidget";

export function VMRoute(): React.ReactElement {
  const { uuid } = useParams();

  const [vm, setVM] = React.useState<VMInfo>();

  const load = async () => {
    setVM(await VMApi.GetSingle(uuid!));
  };

  return (
    <AsyncWidget
      loadKey={uuid}
      load={load}
      errMsg="Failed to load VM information!"
      build={() => <VMRouteBody vm={vm!} />}
    />
  );
}

function VMRouteBody(p: { vm: VMInfo }): React.ReactElement {
  const navigate = useNavigate();

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

  return (
    <VirtWebRouteContainer
      label={`VM ${p.vm.name}`}
      actions={
        <span style={{ display: "inline-flex", alignItems: "center" }}>
          <VMStatusWidget vm={p.vm} onChange={setState} />

          <RouterLink to={p.vm.XMLURL}>
            <Tooltip title="View domain definition">
              <IconButton size="small">
                <Icon path={mdiXml} style={{ width: "1em" }} />
              </IconButton>
            </Tooltip>
          </RouterLink>

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

          {(state === "Shutdown" || state === "Shutoff") && (
            <Button
              variant="contained"
              style={{ marginLeft: "15px" }}
              onClick={() => navigate(p.vm.EditURL)}
            >
              Edit
            </Button>
          )}
        </span>
      }
    >
      <VMDetails
        vm={p.vm}
        editable={false}
        screenshot={p.vm.vnc_access && state === "Running"}
      />
    </VirtWebRouteContainer>
  );
}
