import React from "react";
import { Account } from "../../api/AccountApi";
import { SelectAccountDialog } from "../../dialogs/SelectAccountDialog";

type DialogContext = (
  title: string,
  description: string | React.ReactElement,
  confirmButton?: string,
  excludedAccounts?: Account[]
) => Promise<Account | undefined>;

const DialogContextK = React.createContext<DialogContext | null>(null);

export function ChooseAccountDialogProvider(
  p: React.PropsWithChildren
): React.ReactElement {
  const [title, setTitle] = React.useState("");
  const [description, setDescription] = React.useState<
    string | React.ReactElement
  >("");
  const [confirmButton, setConfirmButton] = React.useState<
    string | undefined
  >();
  const [excludedAccounts, setExcludedAccounts] = React.useState<
    Account[] | undefined
  >();
  const [open, setOpen] = React.useState(false);

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

  const handleClose = (res?: Account) => {
    setOpen(false);

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

  const hook: DialogContext = (
    title,
    description,
    confirmButton,
    excludedAccounts
  ) => {
    setTitle(title);
    setDescription(description);
    setConfirmButton(confirmButton);
    setExcludedAccounts(excludedAccounts);
    setOpen(true);

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

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

      {open && (
        <SelectAccountDialog
          open={open}
          onClose={handleClose}
          onSelected={handleClose}
          title={title}
          description={description}
          confirmButton={confirmButton}
          excludedAccounts={excludedAccounts}
        />
      )}
    </>
  );
}

export function useSelectAccount(): DialogContext {
  return React.use(DialogContextK)!;
}
