type ConfirmDialogOptions = {
  title: string;
  description: string;
  affirmativeLabel: string;
  onAffirmative: () => void;
  dismissLabel: string;
  onDismiss?: () => void;
};

let confirmDialogOnAffirmative: (() => void) | undefined;
let confirmDialogOnDismiss: (() => void) | undefined;

const showConfirmDialog = (options: ConfirmDialogOptions) => {
  confirmDialogOnAffirmative = options.onAffirmative;
  confirmDialogOnDismiss = options.onDismiss;

  $("#confirmDialogTitle").html(options.title);
  $("#confirmDialogDescription").html(options.description);
  $("#confirmDialogAffirmativeButton").html(options.affirmativeLabel);
  $("#confirmDialogDismissButton").html(options.dismissLabel).show();

  $("#confirmDialogOverlay").removeAttr("hidden");
};

// The app's replacement for window.alert: the same panel with a single
// button (and the dismiss button hidden). Clicking outside closes it too.
// hide()/show() rather than the hidden attribute: the button classes set
// display themselves, which beats the browser's [hidden] rule.
const showAlertDialog = ({
  title,
  description,
  buttonLabel = t("dialog.ok"),
  onClose,
}: {
  title: string;
  description: string;
  buttonLabel?: string;
  onClose?: () => void;
}) => {
  confirmDialogOnAffirmative = onClose;
  confirmDialogOnDismiss = onClose;

  $("#confirmDialogTitle").html(title);
  $("#confirmDialogDescription").html(description);
  $("#confirmDialogAffirmativeButton").html(buttonLabel);
  $("#confirmDialogDismissButton").hide();

  $("#confirmDialogOverlay").removeAttr("hidden");
};

const isConfirmDialogOpen = (): boolean => !$("#confirmDialogOverlay").is("[hidden]");

// Whether any of the app's modal layers is open: this dialog, the export
// overlay (export.ts) or the account dialog (account.ts, which owns its own
// check). The keyboard handlers in history.ts and interactions.ts stand
// down while one is, so a Cmd+Z or Backspace meant for the dialog never
// edits the room behind it.
const isModalOverlayOpen = (): boolean =>
  exportPreviewVisible || isConfirmDialogOpen() || isAccountDialogOpen();

const closeConfirmDialog = () => {
  $("#confirmDialogOverlay").attr("hidden", "hidden");
  confirmDialogOnAffirmative = undefined;
  confirmDialogOnDismiss = undefined;
};

const handleConfirmDialogAffirmative = () => {
  const action = confirmDialogOnAffirmative;
  closeConfirmDialog();
  action?.();
};

const handleConfirmDialogDismiss = () => {
  const action = confirmDialogOnDismiss;
  closeConfirmDialog();
  action?.();
};
