import React, { useRef, useCallback } from "react"
import { CSSTransition } from "react-transition-group"

import { DialogProps } from "./interface"
import "./styles/index.css"
import Portal from "@components/Portal"
import Backdrop from "@components/Backdrop"

/**
 * dialog组件用于特定元素或其部分的强调。
 *
 *
 * ### 引用方法
 * ```tsx
 * import { Dialog } from "@atomintl/exchange-ui"
 * ```
 */
const Dialog: React.FC<DialogProps> = props => {
  const { open, hideBackdrop, disableBackdropClick, unmountOnExit, children, onClose } = props

  const nodeRef = useRef(null)

  const containerRef = useRef(null)

  const onCloseDialog = useCallback(
    (event?: React.MouseEvent<HTMLElement>) => {
      //    (event?.target as HTMLElement)?.className

      if (event?.target == containerRef.current && !disableBackdropClick) {
        onClose()
      }
    },
    [disableBackdropClick, onClose]
  )

  return (
    <Portal>
      <CSSTransition in={open} nodeRef={nodeRef} timeout={200} unmountOnExit={unmountOnExit} classNames="nts-dialog">
        <div ref={nodeRef} className="nts-dialog-root">
          <Backdrop open={open} timeout={200} hideBackdrop={hideBackdrop} className="nts-dialog-backdrop" />
          {/* onClick={() => !disableBackdropClick && onClose()} */}
          <div ref={containerRef} className="nts-dialog-container" onClick={onCloseDialog}>
            <div className="nts-dialog-paper">{children}</div>
          </div>
        </div>
      </CSSTransition>
    </Portal>
  )
}

Dialog.defaultProps = {
  open: false,
  hideBackdrop: false,
  disableBackdropClick: false,
  unmountOnExit: true
}

export { DialogProps } from "./interface"
export default Dialog
