import { X } from "lucide-react"
import * as React from "react"
import { cn } from "@/lib/utils"

interface InputProps extends React.ComponentProps<"input"> {
  clearable?: boolean
  onClear?: () => void
}

function Input({
  className,
  type,
  clearable,
  onClear,
  value,
  onChange,
  ...props
}: InputProps) {
  const [showClear, setShowClear] = React.useState(false)
  const inputRef = React.useRef<HTMLInputElement>(null)

  const hasValue =
    value !== undefined && value !== null && String(value).length > 0

  // 监听输入框焦点状态
  const handleFocus = () => setShowClear(true)
  const handleBlur = () => setShowClear(false)

  const handleClear = () => {
    if (onClear) {
      onClear()
    } else if (onChange) {
      // 触发 React 的 change 事件
      const event = {
        target: { value: "" },
        currentTarget: { value: "" },
      } as React.ChangeEvent<HTMLInputElement>
      onChange(event)
    }
    // 清空后重新聚焦
    inputRef.current?.focus()
  }

  return (
    <div className="relative inline-block w-full">
      <input
        ref={inputRef}
        type={type}
        data-slot="input"
        value={value}
        onChange={onChange}
        onFocus={handleFocus}
        onBlur={handleBlur}
        className={cn(
          "file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input h-9 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 disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 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",
          // 当有清空按钮时，右侧留出空间
          clearable && hasValue && showClear && "pr-7",
          className,
        )}
        {...props}
      />
      {clearable && hasValue && showClear && (
        <button
          type="button"
          onClick={handleClear}
          className="absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground"
          aria-label="清空"
        >
          <X className="h-4 w-4" />
        </button>
      )}
    </div>
  )
}

export { Input }
