import * as React from "react"
import { cn } from "@admin/lib/utils"

function Input({
  className,
  type = "text",
  disabled,
  onFocus,
  onMouseUp,
  ...props
}: React.ComponentProps<"input">) {
  const inputRef = React.useRef<HTMLInputElement | null>(null)

  // Utility to move caret to end (safe-guarded)
  const moveCaretToEnd = (el?: HTMLInputElement | null) => {
    if (!el) return
    const len = el.value?.length ?? 0
    // run after UA selection — requestAnimationFrame is reliable here
    requestAnimationFrame(() => {
      try {
        el.setSelectionRange(len, len)
      } catch {
        /* ignore if not supported */
      }
    })
  }

  // If the input is already focused when mounted / value changed (modal opened), move caret.
  React.useEffect(() => {
    const el = inputRef.current
    if (!el) return
    if (document.activeElement === el) moveCaretToEnd(el)
  }, [props.value]) // re-run when value changes; useful when modal injects values

  // Focus handler: keep caret at end, then call user's onFocus if provided.
  const handleFocus = (e: React.FocusEvent<HTMLInputElement>) => {
    moveCaretToEnd(e.target)
    if (onFocus) onFocus(e)
  }

  // Prevent mouseup from selecting the text (when user clicked to focus)
  const handleMouseUp = (e: React.MouseEvent<HTMLInputElement>) => {
    // Prevent default selection-from-mouseup behavior
    e.preventDefault()
    // ensure caret still at end
    moveCaretToEnd(inputRef.current)
    if (onMouseUp) onMouseUp(e)
  }

  return (
    <input
      ref={inputRef}
      type={type}
      data-slot="input"
      disabled={disabled}
      autoComplete="off"
      onFocus={handleFocus}
      onMouseUp={handleMouseUp}
      className={cn(
        "border-input file:text-foreground placeholder:text-gray-400 selection:bg-primary selection:text-primary-foreground flex h-10 w-full min-w-0 rounded-md border bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium md:text-sm",
        "focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]",
        "aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
        disabled ? "cursor-not-allowed opacity-50" : "",
        className
      )}
      {...props}
    />
  )
}

export { Input }
