import React, { useRef } from 'react';
import clsx from 'clsx';
import { DialogOverlay, DialogContent } from '@reach/dialog';

import { MountTransition } from '../transition';

import './modal.scss';

/*
                      _       _
                      | |     | |
  _ __ ___   ___   __| | __ _| |
  | '_ ` _ \ / _ \ / _` |/ _` | |
  | | | | | | (_) | (_| | (_| | |
  |_| |_| |_|\___/ \__,_|\__,_|_|

  NOTES
  - this is based on the Reach UI Dialog https://reach.tech/dialog

*/
export function Modal({
  isOpen,
  setIsOpen,
  duration = 125,
  className,
  children,
  /* overlay props */
  initialFocusRef,
  allowPinchZoom,
  dangerouslyBypassFocusLock,
  dangerouslyBypassScrollLock,
  /* other */
  ...restProps
} = {}) {
  const overlayRef = useRef(null);
  const contentRef = useRef(null);
  return (
    <MountTransition
      on={isOpen}
      name="xn-modal-overlay"
      duration={duration}
      nodeRef={overlayRef}
      mountOnEnter
    >
      <DialogOverlay
        onDismiss={() => setIsOpen(false)}
        ref={overlayRef}
        className={
          isOpen
            ? `xn-modal-overlay-active xn-modal-overlay-enter-active xn-modal-overlay-enter-from`
            : `xn-modal-overlay-active xn-modal-overlay-leave-active xn-modal-overlay-leave-from`
        }
        {...{ initialFocusRef, allowPinchZoom, dangerouslyBypassFocusLock, dangerouslyBypassScrollLock }}
      >
        <MountTransition on={isOpen} name="xn-modal-content" duration={duration} nodeRef={contentRef}>
          <DialogContent
            aria-label="testing"
            ref={contentRef}
            className={clsx(
              isOpen
                ? `xn-modal-content-active xn-modal-content-enter-active xn-modal-content-enter-from`
                : `xn-modal-content-active xn-modal-content-leave-active xn-modal-content-leave-from`,
              className,
            )}
            {...restProps}
          >
            {children}
          </DialogContent>
        </MountTransition>
      </DialogOverlay>
    </MountTransition>
  );
}
