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

export type NumberFieldInputProps = JSX.InputHTMLAttributes<HTMLInputElement>;

/**
 * The spinbutton input element. Supports ArrowUp/ArrowDown keyboard navigation.
 */
export function NumberFieldInput(props: NumberFieldInputProps): JSX.Element {
  const [local, rest] = splitProps(props, [
    "id",
    "aria-describedby",
    "disabled",
    "onKeyDown",
  ]);
  const ctx = useNumberFieldContext();

  const handleKeyDown: JSX.EventHandlerUnion<HTMLInputElement, KeyboardEvent> = (e) => {
    if (e.key === "ArrowUp") {
      e.preventDefault();
      ctx.increment();
    } else if (e.key === "ArrowDown") {
      e.preventDefault();
      ctx.decrement();
    }
    if (typeof local.onKeyDown === "function") {
      local.onKeyDown(e);
    }
  };

  return (
    <input
      id={local.id ?? ctx.inputId()}
      role="spinbutton"
      inputMode="numeric"
      aria-valuenow={ctx.value()}
      aria-valuemin={ctx.min()}
      aria-valuemax={ctx.max()}
      aria-describedby={local["aria-describedby"] ?? ctx.descriptionId()}
      disabled={local.disabled ?? ctx.disabled()}
      value={ctx.value()}
      onKeyDown={handleKeyDown}
      {...rest}
    />
  );
}
