import React, { useEffect, useId, useRef } from 'react';
import Portal from './Portal.jsx';

const FOCUSABLE = 'a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';

/**
 * Confirmation dialog with the legacy popup classes (.ssgs_popup-container / -content).
 *
 * Esc and a backdrop click close it, Tab stays inside, and focus returns to the
 * element that opened it. Rendered in a Portal so it always covers the whole screen.
 *
 * @param {Object}   props
 * @param {string}   props.title       Heading.
 * @param {string}   props.description Body text.
 * @param {boolean}  props.warning     Show the red warning icon.
 * @param {Function} props.onClose     Esc, backdrop and close button.
 * @param {Object}   props.children    Buttons (rendered in .ssgs_button_section).
 */
const Modal = ({ title, description, warning = false, onClose, children }) => {
  const titleId = useId();
  const contentRef = useRef(null);

  useEffect(() => {
    const previousFocus = document.activeElement;
    const focusable = () => Array.from(contentRef.current?.querySelectorAll(FOCUSABLE) || []);
    (focusable()[1] || focusable()[0] || contentRef.current)?.focus();

    const onKeyDown = (e) => {
      if (e.key === 'Escape') {
        e.stopPropagation();
        onClose();
        return;
      }
      if (e.key !== 'Tab') return;
      const items = focusable();
      if (!items.length) return;
      const first = items[0];
      const last = items[items.length - 1];
      if (e.shiftKey && document.activeElement === first) {
        e.preventDefault();
        last.focus();
      } else if (!e.shiftKey && document.activeElement === last) {
        e.preventDefault();
        first.focus();
      }
    };

    document.addEventListener('keydown', onKeyDown, true);
    return () => {
      document.removeEventListener('keydown', onKeyDown, true);
      if (previousFocus && previousFocus.focus) previousFocus.focus();
    };
  }, [onClose]);

  return (
    <Portal>
      <div className="ssgs_popup-container osgsw-modal" onMouseDown={(e) => e.target === e.currentTarget && onClose()} role="presentation">
        <div ref={contentRef} className="ssgs_popup-content" role="dialog" aria-modal="true" aria-labelledby={titleId} tabIndex={-1}>
          <button type="button" className="close ssgs_close_button" onClick={onClose} aria-label="Close">
            &times;
          </button>
          <div className="profile-section">
            {warning && (
              <div className="profile-image">
                <span className="dashicons dashicons-warning" aria-hidden="true" />
              </div>
            )}
            <div className="profile-details">
              <h3 id={titleId} className="profile-title">{title}</h3>
              {description && <p className="profile-description">{description}</p>}
            </div>
          </div>
          <div className="ssgs_first_section">
            <div className="ssgs_button_section">{children}</div>
          </div>
        </div>
      </div>
    </Portal>
  );
};

export default Modal;
