// Rôle : affiche la modale d'import texte partagée par les outils compatibles.
import { useEffect } from "react";
import { createPortal } from "react-dom";
import { Icon } from "../../../components/Icon.jsx";
import { lockBodyScroll } from "../../../utils/bodyScrollLock.js";

export function TextImportModal({ title, value, placeholder, submitLabel, onChange, onSubmit, onClose }) {
  useEffect(() => {
    function handleKeyDown(event) {
      if (event.key === "Escape") onClose();
    }

    const unlock = lockBodyScroll();
    document.addEventListener("keydown", handleKeyDown);
    return () => {
      unlock();
      document.removeEventListener("keydown", handleKeyDown);
    };
  }, [onClose]);

  return createPortal(
    <div className="confirm-modal-root text-import-modal-root">
      <div className="confirm-backdrop" onClick={onClose} />
      <section className="confirm-modal text-import-modal-dialog" role="dialog" aria-modal="true" aria-labelledby="text-import-title">
        <header>
          <h2 id="text-import-title">{title}</h2>
          <button className="drawer-close-button" type="button" onClick={onClose} aria-label="Fermer" title="Fermer">
            <Icon name="close" />
          </button>
        </header>
        <form className="text-import-modal-form" onSubmit={onSubmit}>
          <textarea
            autoFocus
            value={value}
            onChange={(event) => onChange(event.target.value)}
            placeholder={placeholder}
            rows={9}
          />
          <footer>
            <button type="button" onClick={onClose}>Annuler</button>
            <button className="primary" type="submit">{submitLabel}</button>
          </footer>
        </form>
      </section>
    </div>,
    document.body
  );
}
