import {
  CircularProgress,
  Dialog,
  DialogContent,
  DialogContentText,
} from "@mui/material";
import React, { type 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(0);

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

  const hook: LoadingMessageContext = {
    show(message) {
      setMessage(message);
      setOpen((v) => v + 1);
    },
    hide() {
      setOpen((v) => v - 1);
    },
  };

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

      <Dialog open={open > 0}>
        <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)!;
}
