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

/** Props for the button that toggles an Accordion item open/closed. */
export interface AccordionTriggerProps extends JSX.ButtonHTMLAttributes<HTMLButtonElement> {
  children?: JSX.Element;
}

/** Button that toggles an Accordion item open/closed. Supports ArrowDown/ArrowUp/Home/End navigation. */
export function AccordionTrigger(props: AccordionTriggerProps): JSX.Element {
  const [local, rest] = splitProps(props, ["children"]);
  const rootCtx = useAccordionRootContext();
  const itemCtx = useAccordionItemContext();

  return (
    <button
      type="button"
      id={itemCtx.triggerId}
      aria-expanded={itemCtx.isExpanded() ? "true" : "false"}
      aria-controls={itemCtx.contentId}
      data-state={itemCtx.isExpanded() ? "open" : "closed"}
      data-accordion-trigger
      disabled={rootCtx.disabled() || itemCtx.disabled()}
      {...rest}
      onClick={(e) => {
        if (typeof rest.onClick === "function") rest.onClick(e);
        if (!rootCtx.disabled() && !itemCtx.disabled()) rootCtx.toggleItem(itemCtx.value);
      }}
      onKeyDown={(e) => {
        if (typeof rest.onKeyDown === "function") rest.onKeyDown(e);
        const accordion = (e.currentTarget as HTMLButtonElement).closest("[data-accordion-root]");
        if (!accordion) return;
        const triggers = Array.from(
          accordion.querySelectorAll<HTMLButtonElement>("[data-accordion-trigger]"),
        );
        const index = triggers.indexOf(e.currentTarget as HTMLButtonElement);
        if (e.key === "ArrowDown") {
          e.preventDefault();
          triggers[(index + 1) % triggers.length]?.focus();
        } else if (e.key === "ArrowUp") {
          e.preventDefault();
          triggers[(index - 1 + triggers.length) % triggers.length]?.focus();
        } else if (e.key === "Home") {
          e.preventDefault();
          triggers[0]?.focus();
        } else if (e.key === "End") {
          e.preventDefault();
          triggers[triggers.length - 1]?.focus();
        }
      }}
    >
      {local.children}
    </button>
  );
}
