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

type DialogContext = () => Promise<NewCalendarURL | undefined>;

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

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

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

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

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

  const hook: DialogContext = () => {
    setOpen(true);

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

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

      {open && (
        <CreateAccommodationCalendarURLDialog
          open={open}
          onClose={handleClose}
          onSubmitted={handleClose}
        />
      )}
    </>
  );
}

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