'use client';

import { useDebouncedOnChangeCallback, useFocus } from './hooks';
import { Input } from '@repo/ui/components/ui/input';
import { Label } from '@repo/ui/components/ui/label';
import { type ChangeEvent, useState } from 'react';

type FieldProps = {
  readonly disabled?: boolean;
  readonly id: string;
  readonly label: string;
  readonly min?: number;
  readonly onChange?: (value: null | number) => void;
  readonly readOnly?: boolean;
  readonly value: null | number;
};

export function NumberField({
  disabled = false,
  id,
  label,
  min,
  onChange,
  readOnly,
  value: initialValue,
}: FieldProps) {
  const [value, setValue] = useState(initialValue?.toString() ?? '');
  const { debouncedCallback, isPending } = useDebouncedOnChangeCallback<null | number>(onChange);
  const inputRef = useFocus(isPending);

  const handleChange = (event: ChangeEvent<HTMLInputElement>) => {
    const newValue = event.target.value;
    setValue(newValue);

    // Преобразуем строку в число или null
    const numericValue = newValue === '' ? null : Number(newValue);

    // Проверяем, что это валидное число
    if (numericValue === null || (!Number.isNaN(numericValue) && numericValue >= 0)) {
      debouncedCallback(numericValue);
    }
  };

  return (
    <div className="space-y-2">
      <Label htmlFor={id}>{label}</Label>
      <Input
        className="bg-secondary outline-none focus:ring-0 focus:ring-offset-0"
        disabled={disabled || isPending}
        id={id}
        min={min}
        onChange={handleChange}
        readOnly={readOnly}
        ref={inputRef}
        type="number"
        value={value}
      />
    </div>
  );
}
