"use client"

import * as React from "react"
import { Input } from "@/components/ui/input"

interface NumericInputProps extends Omit<React.ComponentProps<typeof Input>, "onChange" | "value" | "type"> {
  value: number
  onChange: (value: number) => void
  min?: number
  max?: number
}

/**
 * A text input that behaves like a number input but lets the user type freely.
 * Validates on blur and clamps to min/max.
 */
function NumericInput({ value, onChange, min = 1, max, className, ...props }: NumericInputProps) {
  const [display, setDisplay] = React.useState(String(value))

  // Sync external value changes
  React.useEffect(() => {
    setDisplay(String(value))
  }, [value])

  const clamp = (v: number) => {
    let n = v
    if (min !== undefined) n = Math.max(min, n)
    if (max !== undefined) n = Math.min(max, n)
    return n
  }

  const commit = (raw: string) => {
    const parsed = parseInt(raw, 10)
    if (Number.isFinite(parsed)) {
      const clamped = clamp(parsed)
      onChange(clamped)
      setDisplay(String(clamped))
    } else {
      // Reset to current value
      setDisplay(String(value))
    }
  }

  return (
    <Input
      inputMode="numeric"
      pattern="[0-9]*"
      value={display}
      onChange={(e) => setDisplay(e.target.value)}
      onBlur={() => commit(display)}
      onKeyDown={(e) => {
        if (e.key === "Enter") {
          commit(display)
        }
      }}
      className={className}
      {...props}
    />
  )
}

export { NumericInput }
