'use client';

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

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

const RHFNumberPasswordField = ({
	name,
	label,
	isRequired = true,
	placeholder,
	...other
}: IProps & React.InputHTMLAttributes<HTMLInputElement>) => {
	const { control, clearErrors } = useFormContext();
	const [showPassword, setShowPassword] = useState(false);

	const togglePasswordVisibility = () => {
		setShowPassword((prev) => !prev);
	};

	// Allow only digits
	const handleInput = (value: string) => value.replace(/\D/g, '');

	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>
					)}

					<div className="relative">
						<Input
							id={name}
							{...field}
							type={showPassword ? 'text' : 'password'}
							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-sm 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'
						}
              `}
							{...other}
						/>
						<span
							onClick={togglePasswordVisibility}
							className="absolute right-3 top-1/2 transform -translate-y-1/2 cursor-pointer text-gray-400 dark:text-gray-500"
						>
							{showPassword ? (
								<Eye className="h-5 w-5" />
							) : (
								<EyeOff className="h-5 w-5" />
							)}
						</span>
					</div>

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

export default RHFNumberPasswordField;
