import type { JSX } from "solid-js";
import { createUniqueId, splitProps } from "solid-js";
import { AccordionItemContextProvider, useAccordionRootContext } from "./accordion-context";

/** Props for a single collapsible item within an Accordion. */
export interface AccordionItemProps extends JSX.HTMLAttributes<HTMLDivElement> {
  value: string;
  disabled?: boolean;
  children: JSX.Element;
}

/** A single collapsible item within an Accordion. */
export function AccordionItem(props: AccordionItemProps): JSX.Element {
  const [local, rest] = splitProps(props, ["value", "disabled", "children"]);
  const rootCtx = useAccordionRootContext();
  const triggerId = createUniqueId();
  const contentId = createUniqueId();

  const itemCtx = {
    get value() {
      return local.value;
    },
    isExpanded: () => rootCtx.isExpanded(local.value),
    triggerId,
    contentId,
    disabled: () => local.disabled ?? false,
  };

  return (
    <AccordionItemContextProvider value={itemCtx}>
      <div
        data-state={rootCtx.isExpanded(local.value) ? "open" : "closed"}
        data-disabled={local.disabled || undefined}
        {...rest}
      >
        {local.children}
      </div>
    </AccordionItemContextProvider>
  );
}
