import type { JSX } from "solid-js";
import { splitProps } from "solid-js";
import { useToggleGroupContext } from "./toggle-group-context";

export interface ToggleGroupItemProps extends JSX.ButtonHTMLAttributes<HTMLButtonElement> {
  value: string;
  disabled?: boolean;
  children?: JSX.Element;
}

/** A single toggle item within a ToggleGroup. */
export function ToggleGroupItem(props: ToggleGroupItemProps): JSX.Element {
  const [local, rest] = splitProps(props, ["value", "disabled", "children"]);
  const ctx = useToggleGroupContext();

  const isPressed = () => ctx.isPressed(local.value);
  const isDisabled = () => local.disabled || ctx.disabled();

  return (
    <button
      type="button"
      aria-pressed={isPressed() ? "true" : "false"}
      data-state={isPressed() ? "on" : "off"}
      disabled={isDisabled()}
      {...rest}
      onClick={(e) => {
        if (!isDisabled()) {
          if (typeof rest.onClick === "function") rest.onClick(e);
          ctx.onItemPress(local.value);
        }
      }}
    >
      {local.children}
    </button>
  );
}
