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

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

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

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

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

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