import React, { PropsWithChildren } from "react";
import { UpdateAccommodation } from "../../../api/accommodations/AccommodationListApi";
import { UpdateAccommodationDialog } from "../../../dialogs/accommodations/UpdateAccommodationDialog";

type DialogContext = (
  accommodation: UpdateAccommodation,
  create: boolean
) => Promise<UpdateAccommodation | undefined>;

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

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

  const [accommodation, setAccommodation] = React.useState<
    UpdateAccommodation | undefined
  >(undefined);
  const [create, setCreate] = React.useState(false);

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

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

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

  const hook: DialogContext = (accommodation, create) => {
    setAccommodation(accommodation);
    setCreate(create);
    setOpen(true);

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

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

      {open && (
        <UpdateAccommodationDialog
          open={open}
          accommodation={accommodation}
          create={create}
          onClose={handleClose}
          onSubmitted={handleClose}
        />
      )}
    </>
  );
}

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