import React, { PropsWithChildren } from "react";
import { UpdateAccommodationReservation } from "../../../api/accommodations/AccommodationsReservationsApi";
import { UpdateReservationDialog } from "../../../dialogs/accommodations/UpdateReservationDialog";

type DialogContext = (
  reservation: UpdateAccommodationReservation,
  create: boolean
) => Promise<UpdateAccommodationReservation | undefined>;

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

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

  const [reservation, setReservation] = React.useState<
    UpdateAccommodationReservation | undefined
  >(undefined);
  const [create, setCreate] = React.useState(false);

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

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

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

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

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

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

      {open && (
        <UpdateReservationDialog
          open={open}
          reservation={reservation}
          create={create}
          onClose={handleClose}
          onSubmitted={handleClose}
        />
      )}
    </>
  );
}

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