import type { JSX } from "solid-js";
import { createUniqueId, splitProps } from "solid-js";
import {
  type CreateDisclosureStateOptions,
  createDisclosureState,
} from "../../primitives/create-disclosure-state";
import { createRegisterId } from "../../primitives/create-register-id";
import {
  DrawerContextProvider,
  type DrawerSide,
  InternalDrawerContextProvider,
  type InternalDrawerContextValue,
} from "./drawer-context";

import type { DrawerRootProps } from "./drawer.props";
export type { DrawerRootProps } from "./drawer.props";

/**
 * Root component for Drawer. Manages open state and provides context.
 */
export function DrawerRoot(props: DrawerRootProps): JSX.Element {
  const [local] = splitProps(props, ["open", "defaultOpen", "onOpenChange", "side", "children"]);

  const disclosure = createDisclosureState({
    get open() {
      return local.open;
    },
    get defaultOpen() {
      return local.defaultOpen;
    },
    get onOpenChange() {
      return local.onOpenChange;
    },
  } as CreateDisclosureStateOptions);

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

  const internalCtx: InternalDrawerContextValue = {
    isOpen: disclosure.isOpen,
    setOpen: (open) => (open ? disclosure.open() : disclosure.close()),
    side: () => local.side ?? "right",
    contentId: () => contentId,
    titleId,
    setTitleId,
    descriptionId,
    setDescriptionId,
  };

  return (
    <InternalDrawerContextProvider value={internalCtx}>
      <DrawerContextProvider value={{ open: disclosure.isOpen, side: () => local.side ?? "right" }}>
        {local.children}
      </DrawerContextProvider>
    </InternalDrawerContextProvider>
  );
}
