import React, { PropsWithChildren } from "react";
import { AccommodationCalendarURL } from "../../../api/accommodations/AccommodationsCalendarURLApi";
import { InstallCalendarDialog } from "../../../dialogs/accommodations/InstallCalendarDialog";

type DialogContext = (cal: AccommodationCalendarURL) => Promise<void>;

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

export function InstallCalendarDialogProvider(
  p: PropsWithChildren
): React.ReactElement {
  const [cal, setCal] = React.useState<AccommodationCalendarURL | undefined>();

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

  const handleClose = () => {
    setCal(undefined);

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

  const hook: DialogContext = (c) => {
    setCal(c);

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

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

      {cal && <InstallCalendarDialog cal={cal} onClose={handleClose} />}
    </>
  );
}

export function useInstallCalendarDialog(): DialogContext {
  return React.useContext(DialogContextK)!;
}
