import type { JSX } from "solid-js";
import { createUniqueId, splitProps } from "solid-js";
import {
  type CreateDisclosureStateOptions,
  createDisclosureState,
} from "../../primitives/create-disclosure-state";
import { CollapsibleContextProvider, type CollapsibleContextValue } from "./collapsible-context";

export interface CollapsibleRootProps extends JSX.HTMLAttributes<HTMLDivElement> {
  open?: boolean;
  defaultOpen?: boolean;
  onOpenChange?: (open: boolean) => void;
  disabled?: boolean;
  children: JSX.Element;
}

/**
 * Root container for a collapsible section. Manages open/close state.
 */
export function CollapsibleRoot(props: CollapsibleRootProps): JSX.Element {
  const [local, rest] = splitProps(props, [
    "open",
    "defaultOpen",
    "onOpenChange",
    "disabled",
    "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 ctx: CollapsibleContextValue = {
    isOpen: disclosure.isOpen,
    setOpen: (open) => (open ? disclosure.open() : disclosure.close()),
    contentId: () => contentId,
    disabled: () => local.disabled ?? false,
  };

  return (
    <CollapsibleContextProvider value={ctx}>
      <div
        data-state={disclosure.isOpen() ? "open" : "closed"}
        data-disabled={local.disabled || undefined}
        {...rest}
      >
        {local.children}
      </div>
    </CollapsibleContextProvider>
  );
}
