import { useId } from "react";
import { useBackLayer } from "../app/useBackLayer.js";

export function ActionDialog({ open, title, description, children, cancelLabel, confirmLabel, pendingLabel, pending = false, confirmDisabled = false, dismissDisabled = false, tone = "default", onCancel, onConfirm }) {
  const reactId = useId().replaceAll(":", "");
  const titleId = `action-dialog-title-${reactId}`;
  const descriptionId = description ? `action-dialog-description-${reactId}` : undefined;
  const closeDialog = useBackLayer(Boolean(open && !pending && !dismissDisabled), onCancel, `action-dialog-${reactId}`, { preferTop: true });
  if (!open) return null;
  return <div className="action-dialog-backdrop" onPointerDown={(event) => { if (!pending && !dismissDisabled && event.target === event.currentTarget) closeDialog(); }}>
    <section className="action-dialog" role="dialog" aria-modal="true" aria-labelledby={titleId} aria-describedby={descriptionId}>
      <h2 id={titleId}>{title}</h2>
      {description && <p id={descriptionId}>{description}</p>}
      {children}
      <div className={`action-dialog-actions${cancelLabel ? "" : " single"}`}>
        {cancelLabel && <button type="button" className="action-dialog-cancel" autoFocus disabled={pending} onClick={() => closeDialog()}>{cancelLabel}</button>}
        <button type="button" className={`action-dialog-confirm ${tone}`} autoFocus={!cancelLabel} disabled={pending || confirmDisabled} onClick={onConfirm}>{pending ? pendingLabel ?? confirmLabel : confirmLabel}</button>
      </div>
    </section>
  </div>;
}
