import React, { useRef, useState, useEffect } from 'react';
import ReactModal from 'react-modal';
import classNames from 'classnames';
import { faXmark } from '@fortawesome/free-solid-svg-icons/faXmark';
import { FontAwesomeIcon } from '../font-awesome-icon';
import { ACCENT_TYPES, Button, BUTTON_TYPES } from '../button';
import { useElementsSize } from '../hooks/use-elements-size';
import ModalService from './modal-service';
import { useTranslation } from '../hooks/use-translation';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
/** A modal dialog with configurable layout
 * @midnight-gray-supported.
 * @alpine-light-supported.
 * */
export const Modal = ({
  show,
  contentClassName,
  modalBodyClassName,
  header,
  title,
  children,
  footer,
  hideFooter,
  hideHeader,
  disableConfirmButton,
  testId,
  disableDismissButton,
  formId,
  aria,
  onConfirmModal = () => {},
  onDismissModal = () => {},
  confirmButtonText: confirmButtonTextParam,
  dismissButtonText,
  labelText,
  modalKey = 'modal-key',
  isLoading = false,
  shouldCloseOnEsc = true,
  shouldCloseOnOverlayClick = true,
  showConfirmButton = true,
  showDismissButton = false,
  confirmButtonTooltip,
  confirmButtonAccentType = ACCENT_TYPES.PRIMARY,
  showCloseIcon = true,
  forceOpen = false,
  // TODO = UIUX-7357 Set to false once the cases that need this set it explicitly
  supportsStacking = false,
  overlayClassName = '',
  closeButtonTestId = 'close-button',
  contentRef
}) => {
  const {
    t
  } = useTranslation();
  const confirmButtonText = confirmButtonTextParam ?? t('OK');
  const modalBodyRef = useRef(null);
  const modalService = ModalService.getInstance();
  const [hasScrollbar, setHasScrollbar] = useState(false);
  const [, height] = useElementsSize(modalBodyRef, true);
  const handleDismiss = e => {
    e?.stopPropagation();
    onDismissModal(e);
  };
  const handleConfirm = e => {
    e?.stopPropagation();
    onConfirmModal(e);
  };
  const onRequestClose = e => {
    const onRequestCloseHandler = showDismissButton ? handleDismiss : handleConfirm;
    onRequestCloseHandler(e);
  };
  const handleRegisterModal = () => {
    modalService?.closeAllDropdowns();
    modalService?.registerModal({
      key: modalKey,
      triggerClose: onRequestClose,
      forceOpen,
      supportsStacking
    });
    setHasScrollbar(!!modalBodyRef.current && modalBodyRef.current.clientHeight !== modalBodyRef.current.scrollHeight);
  };
  const handleClearModal = () => {
    modalService?.clearModal(modalKey);
  };
  const confirmButtonHandlerProps = formId ? {
    formId,
    type: BUTTON_TYPES.SUBMIT
  } : {
    onClick: handleConfirm,
    type: BUTTON_TYPES.BUTTON
  };
  useEffect(() => {
    if (modalBodyRef.current && height) {
      setHasScrollbar(modalBodyRef.current.scrollHeight > height);
    } else {
      setHasScrollbar(false);
    }
  }, [height]);
  return /*#__PURE__*/_jsxs(ReactModal, {
    isOpen: show,
    testId: testId,
    className: classNames('r-modal-content', contentClassName),
    onRequestClose: onRequestClose,
    shouldCloseOnEsc: shouldCloseOnEsc,
    shouldCloseOnOverlayClick: shouldCloseOnOverlayClick,
    overlayClassName: {
      base: `r-modal-overlay ${overlayClassName}`,
      afterOpen: 'r-modal-overlay-open',
      beforeClose: 'r-modal-overlay-close'
    },
    bodyOpenClassName: "modal-open",
    ariaHideApp: false // TODO: I don't know how to do `ReactModal.setAppElement` right. leaving this here for now
    ,
    onAfterOpen: handleRegisterModal,
    onAfterClose: handleClearModal,
    contentRef: contentRef,
    aria: aria ?? {
      label: t('Modal')
    },
    children: [!hideHeader && (header ? /*#__PURE__*/_jsx("div", {
      className: "dr-modal-header",
      children: header
    }) : /*#__PURE__*/_jsxs("div", {
      className: "dr-modal-header",
      "test-id": "dr-modal-header",
      children: [/*#__PURE__*/_jsx("h2", {
        className: "title",
        "test-id": "dr-modal-header-title",
        children: title
      }), showCloseIcon && /*#__PURE__*/_jsx("button", {
        "test-id": closeButtonTestId,
        onClick: onRequestClose,
        className: "close button command round-icon-button",
        "aria-label": labelText ?? t('Close'),
        type: BUTTON_TYPES.BUTTON,
        disabled: showDismissButton ? disableDismissButton : disableConfirmButton,
        children: /*#__PURE__*/_jsx(FontAwesomeIcon, {
          icon: faXmark
        })
      })]
    })), /*#__PURE__*/_jsx("div", {
      ref: modalBodyRef,
      className: classNames('dr-modal-body', modalBodyClassName, {
        'scroll-bar-present': show && hasScrollbar
      }),
      children: children
    }), !hideFooter && (footer ? /*#__PURE__*/_jsx("div", {
      className: "dr-modal-footer",
      children: footer
    }) : /*#__PURE__*/_jsxs("div", {
      className: "dr-modal-footer",
      children: [showConfirmButton && /*#__PURE__*/_jsx(Button, {
        ...confirmButtonHandlerProps,
        className: "dr-modal-confirm-button",
        accentType: confirmButtonAccentType,
        testId: "modal-close",
        isDisabled: disableConfirmButton,
        isLoading: isLoading,
        loadingText: confirmButtonText,
        tooltipText: confirmButtonTooltip,
        children: confirmButtonText
      }), showDismissButton && /*#__PURE__*/_jsx(Button, {
        accentType: ACCENT_TYPES.SECONDARY,
        onClick: handleDismiss,
        testId: "modal-dismiss",
        isDisabled: disableDismissButton || isLoading,
        type: BUTTON_TYPES.BUTTON,
        children: dismissButtonText ?? t('Close')
      })]
    }))]
  });
};