import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Controller, useFormContext } from 'react-hook-form';

interface IProps {
	name: string;
	label: string;
	isRequired?: boolean;
	placeholder?: string;
}

const RHFNumberField = ({
	name,
	label,
	isRequired = true,
	placeholder,
	...other
}: IProps & React.InputHTMLAttributes<HTMLInputElement>) => {
	const { control, clearErrors } = useFormContext();

	// Function to allow only digits
	const handleInput = (value: string) => {
		return value.replace(/\D/g, ''); // remove non-digit characters
	};

	return (
		<Controller
			name={name}
			control={control}
			render={({ field, fieldState: { error } }) => (
				<div className="space-y-1 relative">
					{label && (
						<Label className="text-sm font-medium mb-1 block">
							{label}{' '}
							{isRequired ? (
								<span className="text-red-500 align-middle">*</span>
							) : (
								<span className="text-gray-400 font-normal text-[10px]">
									(optional)
								</span>
							)}
						</Label>
					)}

					<Input
						id={name}
						type="text" // keep type as string
						{...field}
						placeholder={placeholder}
						onChange={(e) => {
							const digitsOnly = handleInput(e.target.value);
							field.onChange(digitsOnly);
							clearErrors(name);
						}}
						className={`w-full h-10 rounded-md border py-2 ps-3 text-[16px] font-normal placeholder:text-xs placeholder:font-light
              focus:ring-0 focus:ring-offset-0 focus-visible:ring-[0.3px] focus-visible:outline-none
              ${
						error
							? 'border-red-500'
							: 'border-gray-300 dark:border-gray-600'
					}
             focus:ring-primary focus:border-ring`}
						{...other}
					/>

					{error && (
						<p className="text-red-500 text-sm mt-1">{error.message}</p>
					)}
				</div>
			)}
		/>
	);
};

export default RHFNumberField;
