import type { JSX } from "solid-js";
import { createSignal, splitProps } from "solid-js";
import { AccordionRootContextProvider, type AccordionRootContextValue } from "./accordion-context";

/** Props for the root accordion container that manages expanded state. */
export interface AccordionRootProps extends JSX.HTMLAttributes<HTMLDivElement> {
  /** "single" allows one item open at a time; "multiple" allows any number. @default "single" */
  type?: "single" | "multiple";
  /** In single mode, whether the open item can be closed by clicking it again. @default false */
  collapsible?: boolean;
  value?: string | string[];
  defaultValue?: string | string[];
  onValueChange?: (value: string | string[]) => void;
  disabled?: boolean;
  children: JSX.Element;
}

/**
 * Root container for an accordion. Manages which items are expanded.
 */
export function AccordionRoot(props: AccordionRootProps): JSX.Element {
  const [local, rest] = splitProps(props, [
    "type",
    "collapsible",
    "value",
    "defaultValue",
    "onValueChange",
    "disabled",
    "children",
  ]);

  const type = () => local.type ?? "single";

  const normalize = (v: string | string[] | undefined): string[] => {
    if (v === undefined) return [];
    return Array.isArray(v) ? v : [v];
  };

  const [expandedValues, setExpandedValues] = createSignal<string[]>(normalize(local.defaultValue));

  const getValues = (): string[] =>
    local.value !== undefined ? normalize(local.value) : expandedValues();

  const ctx: AccordionRootContextValue = {
    isExpanded: (value) => getValues().includes(value),
    toggleItem: (value) => {
      const current = getValues();
      let next: string[];
      if (type() === "single") {
        if (current.includes(value)) {
          next = local.collapsible ? [] : current;
        } else {
          next = [value];
        }
      } else {
        next = current.includes(value) ? current.filter((v) => v !== value) : [...current, value];
      }
      if (local.value === undefined) setExpandedValues(next);
      local.onValueChange?.(type() === "multiple" ? next : (next[0] ?? ""));
    },
    disabled: () => local.disabled ?? false,
  };

  return (
    <AccordionRootContextProvider value={ctx}>
      <div data-accordion-root data-disabled={local.disabled || undefined} {...rest}>
        {local.children}
      </div>
    </AccordionRootContextProvider>
  );
}
