import { useCallback, useRef, useState } from 'react';
import { Input } from '@/components/ui/input';

type PhoneNumberInputProps = {
    name?: string;
    defaultValue?: string;
    placeholder?: string;
    disabled?: boolean;
    className?: string;
};

function formatPhone(value: string | null | undefined): string {
    const digits = (value ?? '').replace(/[^0-9]/g, '');
    const groups: string[] = [];
    for (let i = 0; i < digits.length; i += 4) {
        groups.push(digits.slice(i, i + 4));
    }
    return groups.join(' ');
}

export function PhoneNumberInput({
    name,
    defaultValue = '',
    placeholder = '0812 3456 7890',
    disabled = false,
    className,
}: PhoneNumberInputProps) {
    const [displayValue, setDisplayValue] = useState(formatPhone(defaultValue));
    const lastValidRef = useRef(displayValue);

    const handleChange = useCallback(
        (e: React.ChangeEvent<HTMLInputElement>) => {
            const formatted = formatPhone(e.target.value);
            lastValidRef.current = formatted;
            setDisplayValue(formatted);
        },
        [],
    );

    const handleBlur = useCallback(() => {
        setDisplayValue(lastValidRef.current);
    }, []);

    return (
        <Input
            name={name}
            type="text"
            inputMode="tel"
            value={displayValue}
            onChange={handleChange}
            onBlur={handleBlur}
            placeholder={placeholder}
            disabled={disabled}
            className={className}
            autoComplete="off"
        />
    );
}
