import React, { useCallback, useEffect, useRef } from 'react';
import classNames from 'classnames';
import { faXmark } from '@fortawesome/free-solid-svg-icons/faXmark';
import { ACCENT_TYPES, Button, BUTTON_SIZES } from '../button';
import { FontAwesomeIcon } from '../font-awesome-icon';
import { useFocusTrap } from '../hooks/use-focus-trap';
import { TruncateWithTooltip } from '../truncate-with-tooltip';
import ModalService from '../modal/modal-service';
import { useTranslation } from '../hooks/use-translation';
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
/**
 * Modal window which is rendered next to sidebar.
 * Requirements for parent component of this modal:
 * - position: relative;
 * - no overflow styles;
 * - should be rightmost or leftmost component on the page, like sidebar
 * @midnight-gray-supported
 * @uxr-only-supported
 * @alpine-light-supported
 */
export const SidebarModal = ({
  title,
  children,
  footer,
  onClose = () => {},
  show,
  headerTagName = 'h4',
  headerClassName,
  headerTagClassName,
  contentClassName,
  footerClassName,
  modalBodyClassName,
  testId = 'sidebar-modal',
  closeButtonTestId = 'sidebar-modal-close-button',
  closeLabelText,
  shouldCloseOnEsc = true,
  showCloseIcon = true,
  disableClose = false,
  alignRight = false,
  ariaLabel
}) => {
  const {
    t
  } = useTranslation();
  if (!show) {
    return null;
  }
  return /*#__PURE__*/_jsx(SidebarModalContent, {
    title: title,
    footer: footer,
    onClose: onClose,
    headerTagName: headerTagName,
    headerClassName: headerClassName,
    headerTagClassName: headerTagClassName,
    contentClassName: contentClassName,
    footerClassName: footerClassName,
    modalBodyClassName: modalBodyClassName,
    testId: testId,
    closeButtonTestId: closeButtonTestId,
    closeLabelText: closeLabelText ?? t('Close'),
    shouldCloseOnEsc: shouldCloseOnEsc,
    showCloseIcon: showCloseIcon,
    disableClose: disableClose,
    alignRight: alignRight,
    ariaLabel: ariaLabel ?? t('Sidebar modal'),
    children: children
  });
};

/**
 * This wrapper is required because hooks could not be called conditionally, useFocusTrap will not react on updated ref
 */
function SidebarModalContent({
  title,
  children,
  footer,
  onClose = () => {},
  headerTagName: HeaderTag = 'h4',
  headerClassName,
  headerTagClassName,
  contentClassName,
  footerClassName,
  modalBodyClassName,
  testId,
  closeButtonTestId,
  closeLabelText,
  shouldCloseOnEsc,
  showCloseIcon,
  disableClose,
  alignRight,
  ariaLabel
}) {
  const modalContainerRef = useRef(null);
  const modalService = ModalService.getInstance();
  useFocusTrap(modalContainerRef);
  useEffect(() => {
    const modalKey = 'sidebar-modal';
    // Treat this as a specific case of a modal
    modalService?.closeAllDropdowns();
    modalService?.registerModal({
      key: modalKey,
      triggerClose: onClose,
      forceOpen: false,
      supportsStacking: false
    });
    return () => {
      modalService?.clearModal(modalKey);
    };
  }, [modalService, onClose]);
  useEffect(() => {
    // The modal should get focus when opened, so the following Tab will move focus to the first focusable element within
    modalContainerRef.current?.focus();
  }, []);
  const onKeyPress = useCallback(event => {
    if (shouldCloseOnEsc && !disableClose && event.key === 'Escape') {
      onClose();
    }
  }, [shouldCloseOnEsc, disableClose, onClose]);
  return /*#__PURE__*/_jsxs(_Fragment, {
    children: [/*#__PURE__*/_jsxs("section", {
      // when aria-modal="true", screen readers might limit interaction to the modal content only and, for example, not announce the content of typeahead
      role: "dialog",
      "aria-label": ariaLabel,
      tabIndex: -1 // Shouldn't be navigated directly by pressing Tab, but should be implicitly focusable when modal is opened and .focus() is called.
      ,
      className: classNames('sidebar-modal', modalBodyClassName, {
        'align-right': alignRight
      }),
      "test-id": testId,
      onKeyUp: onKeyPress,
      ref: modalContainerRef,
      children: [/*#__PURE__*/_jsxs("header", {
        className: classNames('sidebar-modal-header', headerClassName),
        children: [/*#__PURE__*/_jsx(TruncateWithTooltip, {
          className: classNames(headerTagClassName),
          children: /*#__PURE__*/_jsx(HeaderTag, {
            className: classNames(headerTagClassName),
            children: title
          })
        }), showCloseIcon && /*#__PURE__*/_jsx(Button, {
          accentType: ACCENT_TYPES.ROUND_ICON,
          onClick: disableClose ? undefined : onClose,
          size: BUTTON_SIZES.XS,
          disabled: disableClose,
          "aria-label": closeLabelText,
          testId: closeButtonTestId,
          children: /*#__PURE__*/_jsx(FontAwesomeIcon, {
            icon: faXmark
          })
        })]
      }), /*#__PURE__*/_jsx("div", {
        className: classNames('sidebar-modal-content', contentClassName),
        children: children
      }), !!footer && /*#__PURE__*/_jsx("footer", {
        className: classNames('sidebar-modal-footer', footerClassName),
        "test-id": "sidebar-modal-footer",
        children: footer
      })]
    }), /*#__PURE__*/_jsx("div", {
      onClick: disableClose ? undefined : onClose,
      className: classNames('sidebar-modal-backdrop', {
        'align-right': alignRight
      }),
      "test-id": "sidebar-modal-backdrop"
    })]
  });
}