import { Alert, CircularProgress, Typography } from "@mui/material";
import { AsyncWidget } from "../AsyncWidget";
import React from "react";
import { CheckboxInput } from "./CheckboxInput";
import { useAlert } from "../../hooks/providers/AlertDialogProvider";
import { useSnackbar } from "../../hooks/providers/SnackbarProvider";

export function ResAutostartInput(p: {
  editable: boolean;
  checkAutotostart: () => Promise<boolean>;
  setAutotostart: (enable: boolean) => Promise<void>;
  ressourceName: string;
}): React.ReactElement {
  const alert = useAlert();
  const snackbar = useSnackbar();

  const [enabled, setEnabled] = React.useState<boolean | undefined>();

  const load = async () => {
    setEnabled(await p.checkAutotostart());
  };

  const update = async (enabled: boolean) => {
    try {
      await p.setAutotostart(enabled);
      snackbar(`Autostart status of ${p.ressourceName} successfully updated!`);
      setEnabled(enabled);
    } catch (e) {
      console.error(e);
      alert(`Failed to update autostart status of ${p.ressourceName}!`);
    }
  };

  return (
    <AsyncWidget
      loadKey={p.ressourceName}
      load={load}
      errMsg={`Failed to check autostart status of ${p.ressourceName}!`}
      buildLoading={() => (
        <Typography>
          <CircularProgress size={"1rem"} /> Checking for autostart
        </Typography>
      )}
      buildError={(e: string) => <Alert severity="error">{e}</Alert>}
      build={() => (
        <ResAutostartInputInner
          editable={p.editable}
          enabled={enabled!}
          setEnabled={update}
          resName={p.ressourceName}
        />
      )}
    />
  );
}

function ResAutostartInputInner(p: {
  editable: boolean;
  enabled: boolean;
  setEnabled: (b: boolean) => void;
  resName: string;
}): React.ReactElement {
  return (
    <div>
      <CheckboxInput
        editable={p.editable}
        checked={p.enabled}
        label={`Autostart ${p.resName}`}
        onValueChange={p.setEnabled}
      />
    </div>
  );
}
