// Rôle : affiche la modale d'import/export 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, readOnly = false, error = "", info = "", onChange, onSubmit, onCopy, 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
            className={error ? "has-error" : ""}
            readOnly={readOnly}
            value={value}
            onChange={(event) => onChange?.(event.target.value)}
            placeholder={placeholder}
            rows={9}
            aria-invalid={Boolean(error)}
            aria-describedby={error ? "text-import-error" : undefined}
          />
          {info && (
            <p className="text-import-info">
              <Icon name="info" />
              <span>{info}</span>
            </p>
          )}
          {error && (
            <p className="text-import-error" id="text-import-error" role="alert">
              <Icon name="close" />
              <span>{error}</span>
            </p>
          )}
          <footer>
            <button type="button" onClick={onClose}>Annuler</button>
            {readOnly ? (
              <button className="primary" type="button" onClick={onCopy}>{submitLabel}</button>
            ) : (
              <button className="primary" type="submit">{submitLabel}</button>
            )}
          </footer>
        </form>
      </section>
    </div>,
    document.body
  );
}
