import {
  CircularProgress,
  Dialog,
  DialogContent,
  DialogContentText,
} from "@mui/material";
import React, { PropsWithChildren } from "react";

interface LoadingMessageContext {
  show: (message: string) => void;
  hide: () => void;
}

const LoadingMessageContextK =
  React.createContext<LoadingMessageContext | null>(null);

export function LoadingMessageProvider(
  p: PropsWithChildren
): React.ReactElement {
  const [open, setOpen] = React.useState(false);

  const [message, setMessage] = React.useState("");

  const hook: LoadingMessageContext = {
    show(message) {
      setMessage(message);
      setOpen(true);
    },
    hide() {
      setMessage("");
      setOpen(false);
    },
  };

  return (
    <>
      <LoadingMessageContextK value={hook}>
        {p.children}
      </LoadingMessageContextK>

      <Dialog open={open}>
        <DialogContent>
          <DialogContentText>
            <div
              style={{
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
              }}
            >
              <CircularProgress style={{ marginRight: "15px" }} />

              {message}
            </div>
          </DialogContentText>
        </DialogContent>
      </Dialog>
    </>
  );
}

export function useLoadingMessage(): LoadingMessageContext {
  return React.use(LoadingMessageContextK)!;
}
