// packages/core/src/components/number-field/number-field-increment-trigger.tsx
import type { JSX } from "solid-js";
import { splitProps } from "solid-js";
import { useNumberFieldContext } from "./number-field-context";

export interface NumberFieldIncrementTriggerProps
  extends JSX.ButtonHTMLAttributes<HTMLButtonElement> {
  /** Button content. */
  children?: JSX.Element | undefined;
}

/**
 * Button that increments the number field value by the step amount.
 * Automatically disabled when the value reaches the maximum.
 */
export function NumberFieldIncrementTrigger(
  props: NumberFieldIncrementTriggerProps,
): JSX.Element {
  const [local, rest] = splitProps(props, ["children", "onClick", "disabled"]);
  const ctx = useNumberFieldContext();

  const isDisabled = (): boolean => {
    if (local.disabled ?? ctx.disabled()) return true;
    const maxVal = ctx.max();
    if (maxVal !== undefined && ctx.value() >= maxVal) return true;
    return false;
  };

  const handleClick: JSX.EventHandlerUnion<HTMLButtonElement, MouseEvent> = (e) => {
    ctx.increment();
    if (typeof local.onClick === "function") {
      local.onClick(e);
    }
  };

  return (
    <button
      type="button"
      tabIndex={-1}
      aria-label="Increment"
      disabled={isDisabled()}
      onClick={handleClick}
      {...rest}
    >
      {local.children}
    </button>
  );
}
