import { FC, InputHTMLAttributes, useEffect, useState } from 'react' import { clx } from '../helpers/utils'; import { Eye, SearchNormal } from 'iconsax-react'; import { getIconColor } from '@/utils/colorUtils'; import Error from './Error'; type Variant = "floating_outlined" | "primary" | "search"; type Props = { label?: string; className?: string; variant?: Variant; error_text?: string; onEnter?: () => void; unit?: string; seprator?: boolean; isNotRequired?: boolean; onChangeSearchFinal?: (value: string) => void; endIcon?: React.ReactNode; } & InputHTMLAttributes const formatNumber = (value: string | number): string => { if (!value) return ''; const inputValue = String(value).replace(/,/g, ''); return inputValue.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ','); }; const Input: FC = (props: Props) => { const [formattedValue, setFormattedValue] = useState( props.value ? formatNumber(props.value as string) : '' ); const [showPassword, setShowPassword] = useState(false) const [search, setSearch] = useState('') const inputClass = clx( 'w-full input-surface h-10 block px-4 text-xs rounded-xl transition-colors', props.readOnly && 'bg-muted border-0 text-muted-foreground', props.variant === 'search' && 'ps-10', props.className ); const handleInputChange = (event: React.ChangeEvent) => { if (props.seprator) { const inputValue = event.target.value.replace(/,/g, ''); const formatted = formatNumber(inputValue); setFormattedValue(formatted); props.onChange?.({ ...event, target: { ...event.target, value: inputValue, }, }); } else { props.onChange?.(event); } }; useEffect(() => { if (props.value) { setFormattedValue(formatNumber(props.value as string)); } else { setFormattedValue(''); } }, [props.value]) useEffect(() => { if (props.variant === 'search' && props.onChangeSearchFinal) { const timeout = setTimeout(() => { props.onChangeSearchFinal?.(search) }, 1000) return () => clearTimeout(timeout) } }, [search, props]) return ( {props.label} { setSearch(e.target.value) handleInputChange(e) }} value={props.seprator ? formattedValue : props.value} type={props.type === 'password' && showPassword ? 'text' : props.type === 'password' ? 'password' : undefined} className={inputClass} /> { props.type === 'password' && setShowPassword((oldValue) => !oldValue)} size={20} color={getIconColor('muted')} className='absolute top-0 bottom-0 cursor-pointer my-auto left-3' /> } { props.variant === 'search' && } { props.endIcon && {props.endIcon} } { props.error_text && } ) } export default Input