import * as React from 'react';
import { PatternFormat } from 'react-number-format';
import { Input } from '@/components/ui/input';
import { cn } from '@/lib/utils';

interface MaskedInputProps
    extends Omit<
        React.ComponentProps<typeof Input>,
        'onChange' | 'value' | 'type' | 'defaultValue'
    > {
    format: string;
    mask?: string;
    allowEmptyFormatting?: boolean;
    onValueChange?: (values: {
        formattedValue: string;
        value: string;
    }) => void;
    value?: string;
}

/**
 * Masked input component using react-number-format with shadcn Input styling
 *
 * @example NIK (16-digit ID)
 * <MaskedInput format="#### #### #### ####" mask="_" />
 *
 * @example Phone (Indonesian)
 * <MaskedInput format="+62 ### #### ####" mask="_" />
 */
const MaskedInput = React.forwardRef<HTMLInputElement, MaskedInputProps>(
    (
        {
            className,
            format,
            mask = '_',
            allowEmptyFormatting = false,
            onValueChange,
            value,
            ...props
        },
        ref
    ) => {
        return (
            <PatternFormat
                format={format}
                mask={mask}
                allowEmptyFormatting={allowEmptyFormatting}
                value={value}
                onValueChange={(values) => {
                    onValueChange?.({
                        formattedValue: values.formattedValue,
                        value: values.value,
                    });
                }}
                customInput={Input}
                getInputRef={ref}
                className={cn(className)}
                {...props}
            />
        );
    }
);

MaskedInput.displayName = 'MaskedInput';

export { MaskedInput };
