import {
  Button,
  Dialog,
  DialogActions,
  DialogBody,
  DialogContent,
  DialogSurface,
  DialogTitle,
} from "@fluentui/react-components";
import React, { PropsWithChildren } from "react";

type ConfirmContext = (
  message: string,
  title?: string,
  confirmButton?: string,
  cancelButton?: string
) => Promise<boolean>;

const ConfirmContextK = React.createContext<ConfirmContext | null>(null);

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

  const [title, setTitle] = React.useState<string | undefined>(undefined);
  const [message, setMessage] = React.useState("");
  const [confirmButton, setConfirmButton] = React.useState<string | undefined>(
    undefined
  );
  const [cancelButton, setCancelButton] = React.useState<string | undefined>(
    undefined
  );

  const cb = React.useRef<null | ((a: boolean) => void)>(null);

  const handleClose = (confirm: boolean) => {
    setOpen(false);

    if (cb.current !== null) cb.current(confirm);
    cb.current = null;
  };

  const hook: ConfirmContext = (
    message,
    title,
    confirmButton,
    cancelButton
  ) => {
    setTitle(title);
    setMessage(message);
    setConfirmButton(confirmButton);
    setCancelButton(cancelButton);
    setOpen(true);

    return new Promise((res) => {
      cb.current = res;
    });
  };

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

      <Dialog
        open={open}
        onOpenChange={(_event, data) => {
          if (!data.open) setOpen(false);
        }}
      >
        <DialogSurface>
          <DialogBody>
            {title && <DialogTitle>{title}</DialogTitle>}
            <DialogContent>{message}</DialogContent>
            <DialogActions>
              <Button
                onClick={() => handleClose(false)}
                autoFocus
                appearance="secondary"
              >
                {cancelButton ?? "Cancel"}
              </Button>
              <Button onClick={() => handleClose(true)} appearance="primary">
                {confirmButton ?? "Confirm"}
              </Button>
            </DialogActions>
          </DialogBody>
        </DialogSurface>
      </Dialog>
    </>
  );
}

export function useConfirm(): ConfirmContext {
  return React.useContext(ConfirmContextK)!;
}
