import React, { useCallback, useEffect, useRef } from 'react';
import ModalContainer, {
  ModalContainerProps,
} from '@digigov/react-core/ModalContainer';
import useKeypress from '@digigov/ui/utils/hooks/useKeypress';

export interface ModalProps extends ModalContainerProps {
  onEscape?: () => void;
}

export const Modal = React.forwardRef<HTMLDivElement, ModalProps>(
  function Modal({ ...props }, ref) {
    if (props.open) {
      return <ModalBase {...props} ref={ref} />;
    } else {
      return null;
    }
  }
);

export const ModalBase = React.forwardRef<HTMLDivElement, ModalProps>(
  function ModalBase({ open, children, onEscape, ...props }, ref) {
    const firstModalElement = useRef<HTMLSpanElement>(null);
    const lastModalElement = useRef<HTMLSpanElement>(null);
    const handleFocus = useCallback(() => {
      firstModalElement.current?.focus();
    }, []);
    useKeypress('Escape', onEscape);
    useEffect(() => {
      const lastModalElementInstance = lastModalElement.current;
      handleFocus();
      lastModalElementInstance?.addEventListener('focus', handleFocus);
      return () => {
        lastModalElementInstance?.removeEventListener('focus', handleFocus);
      };
    }, []);
    return (
      <ModalContainer
        open={open}
        role="dialog"
        ref={ref}
        aria-hidden="false"
        aria-modal="true"
        {...props}
      >
        <span tabIndex={-1} ref={firstModalElement} />
        {open && children}
        <span tabIndex={0} ref={lastModalElement} />
      </ModalContainer>
    );
  }
);

export default Modal;
