import * as React from 'react';

import { cn } from '@/lib/utils';
import { useControllableValue } from 'ahooks';

type InputSize = 'small' | 'large';

interface InputNumberProps extends Omit<
  React.InputHTMLAttributes<HTMLInputElement>,
  'size' | 'value' | 'onChange' | 'type'
> {
  prefixIcon?: React.ReactNode;
  size?: InputSize;
  error?: boolean;
  value?: number;
  onChange?: (value: number) => void;
  min?: number;
  max?: number;
}

function InputNumber({
  className,
  prefixIcon,
  error = false,
  size = 'large',
  min,
  max,
  ...props
}: InputNumberProps) {
  const [value, onChange] = useControllableValue(props);

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const inputValue = e.target.value;
    // 验证是否为有效数字
    const numValue = parseFloat(inputValue);
    if (isNaN(numValue)) {
      onChange(inputValue);
      return;
    }
    onChange(numValue);
  };

  return (
    <div
      className={cn(
        'relative flex w-full gap-2 items-center',
        error && '[&>input]:border-primary-variant-press'
      )}
    >
      {prefixIcon && (
        <span className="pointer-events-none absolute left-3 flex items-center">{prefixIcon}</span>
      )}
      <input
        type="text"
        inputMode="decimal"
        data-slot="input"
        className={cn(
          'placeholder:text-txt-tertiary-normal bg-surface-element-normal rounded-sm',
          'selection:bg-surface-element-normal selection:text-txt-primary-normal',
          'border border-solid border-transparent',
          'hover:border-outline-hover focus-visible:border-primary-variant-press',
          'transition-[color,box-shadow] outline-none',
          'disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50',
          size === 'small' && 'txt-body-m flex h-8 w-full min-w-0 px-4 py-1',
          size === 'large' && 'txt-body-l flex h-12 w-full min-w-0 px-4 py-1',
          error && '!border-important-variant-normal',
          prefixIcon && 'pl-10',
          className
        )}
        aria-invalid={error}
        {...props}
        value={value}
        onChange={handleChange}
      />
      {min !== undefined && (
        <span className="text-txt-secondary-normal absolute right-3 text-xs select-none">
          {'≥'}
          {min}
        </span>
      )}
    </div>
  );
}

export { InputNumber };
