import type { JSX } from "solid-js";
import { createUniqueId } from "solid-js";
import {
  type CreateDisclosureStateOptions,
  createDisclosureState,
} from "../../primitives/create-disclosure-state";
import { createRegisterId } from "../../primitives/create-register-id";
import {
  AlertDialogContextProvider,
  InternalAlertDialogContextProvider,
  type InternalAlertDialogContextValue,
} from "./alert-dialog-context";

/** Props for the AlertDialog root. */
export interface AlertDialogRootProps {
  /** Controls open state externally. */
  open?: boolean;
  /** Initial open state when uncontrolled. */
  defaultOpen?: boolean;
  /** Called when open state changes. */
  onOpenChange?: (open: boolean) => void;
  children: JSX.Element;
}

/**
 * Root component for AlertDialog. Manages open state and provides context.
 */
export function AlertDialogRoot(props: AlertDialogRootProps): JSX.Element {
  const disclosure = createDisclosureState({
    get open() {
      return props.open;
    },
    get defaultOpen() {
      return props.defaultOpen;
    },
    get onOpenChange() {
      return props.onOpenChange;
    },
  } as CreateDisclosureStateOptions);

  const contentId = createUniqueId();
  const [titleId, setTitleId] = createRegisterId();
  const [descriptionId, setDescriptionId] = createRegisterId();

  const internalCtx: InternalAlertDialogContextValue = {
    isOpen: disclosure.isOpen,
    setOpen: (open) => (open ? disclosure.open() : disclosure.close()),
    contentId: () => contentId,
    titleId,
    setTitleId,
    descriptionId,
    setDescriptionId,
  };

  return (
    <InternalAlertDialogContextProvider value={internalCtx}>
      <AlertDialogContextProvider value={{ open: disclosure.isOpen }}>
        {props.children}
      </AlertDialogContextProvider>
    </InternalAlertDialogContextProvider>
  );
}
