import React, { ReactNode, useCallback, useState } from 'react';
import FocusTrap from 'focus-trap-react';
import { Modal, Overlay, OverlayBackdrop, OverlayCenter, PopOutContainerProvider } from 'folds';
import { stopPropagation } from '../utils/keyboard';

type Modal500Props = {
  requestClose: () => void;
  children: ReactNode;
};
export function Modal500({ requestClose, children }: Modal500Props) {
  const [modalEl, setModalEl] = useState<HTMLDivElement | null>(null);
  const modalRef = useCallback((el: HTMLDivElement | null) => setModalEl(el), []);

  return (
    <Overlay open backdrop={<OverlayBackdrop />}>
      <OverlayCenter>
        <FocusTrap
          focusTrapOptions={{
            initialFocus: false,
            clickOutsideDeactivates: true,
            onDeactivate: requestClose,
            escapeDeactivates: stopPropagation,
          }}
        >
          <Modal ref={modalRef} size="500" variant="Background">
            <PopOutContainerProvider value={modalEl ?? undefined}>
              {children}
            </PopOutContainerProvider>
          </Modal>
        </FocusTrap>
      </OverlayCenter>
    </Overlay>
  );
}
