import type { JSX } from "solid-js";
import { Show, createEffect, onCleanup, splitProps } from "solid-js";
import { createFocusTrap } from "../../utilities/focus-trap/create-focus-trap";
import { createScrollLock } from "../../utilities/scroll-lock/create-scroll-lock";
import { useInternalAlertDialogContext } from "./alert-dialog-context";

/** Props for AlertDialog.Content. */
export interface AlertDialogContentProps extends JSX.HTMLAttributes<HTMLDivElement> {
  forceMount?: boolean;
  children?: JSX.Element;
}

/**
 * AlertDialog content panel. Uses focus trap and scroll lock.
 * Does NOT dismiss on Escape or outside pointer click (unlike Dialog).
 */
export function AlertDialogContent(props: AlertDialogContentProps): JSX.Element {
  const [local, rest] = splitProps(props, ["children", "forceMount"]);
  const ctx = useInternalAlertDialogContext();
  let contentRef: HTMLDivElement | undefined;

  const focusTrap = createFocusTrap(() => contentRef ?? null);
  const scrollLock = createScrollLock();

  createEffect(() => {
    if (ctx.isOpen()) {
      focusTrap.activate();
      scrollLock.lock();
    } else {
      focusTrap.deactivate();
      scrollLock.unlock();
    }
    onCleanup(() => {
      focusTrap.deactivate();
      scrollLock.unlock();
    });
  });

  return (
    <Show when={local.forceMount || ctx.isOpen()}>
      <div
        ref={contentRef}
        id={ctx.contentId()}
        role="alertdialog"
        aria-modal="true"
        aria-labelledby={ctx.titleId() || undefined}
        aria-describedby={ctx.descriptionId() || undefined}
        data-state={ctx.isOpen() ? "open" : "closed"}
        {...rest}
      >
        {local.children}
      </div>
    </Show>
  );
}
