import React, { useEffect } from "react";
import { createPortal } from "react-dom";

/**
 * @param {{
 *   open: boolean,
 *   onClose: () => void,
 *   onConfirm: () => void,
 *   submitting?: boolean,
 *   documentName?: string,
 *   pageCount?: number,
 * }} props
 */
export default function SubmitDocumentConfirmModal({
  open,
  onClose,
  onConfirm,
  submitting = false,
  documentName,
  pageCount = 1,
}) {
  useEffect(() => {
    if (!open) return undefined;
    const prevOverflow = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    return () => {
      document.body.style.overflow = prevOverflow;
    };
  }, [open]);

  if (!open || typeof document === "undefined") return null;

  const pageLabel = `${pageCount} page${pageCount === 1 ? "" : "s"}`;

  return createPortal(
    <div
      className="swi-modal-backdrop swi-modal-backdrop--viewport"
      role="presentation"
      onClick={submitting ? undefined : onClose}
    >
      <div
        className="swi-modal swi-submit-doc-modal"
        role="dialog"
        aria-modal="true"
        aria-labelledby="submit-doc-modal-title"
        onClick={(event) => event.stopPropagation()}
      >
        <header className="swi-modal__head">
          <h2 id="submit-doc-modal-title" className="swi-modal__title">
            Ready to submit?
          </h2>
          <button
            type="button"
            className="swi-modal__close"
            aria-label="Close"
            disabled={submitting}
            onClick={onClose}
          >
            ×
          </button>
        </header>

        <p className="swi-muted swi-submit-doc-modal__intro">
          You are about to complete and submit{" "}
          <strong>{documentName || "this document"}</strong> ({pageLabel}).
          Please confirm that all pages, text, logos, and images are correct.
        </p>
        <p className="swi-submit-doc-modal__note">
          If you are not ready, click <strong>Cancel</strong> to return and
          continue editing.
        </p>

        <div className="swi-modal-actions">
          <button
            type="button"
            className="swi-btn swi-btn--ghost"
            disabled={submitting}
            onClick={onClose}
          >
            Cancel
          </button>
          <button
            type="button"
            className="swi-btn swi-btn--primary"
            disabled={submitting}
            onClick={onConfirm}
          >
            {submitting ? "Submitting…" : "Complete & submit"}
          </button>
        </div>
      </div>
    </div>,
    document.body
  );
}
