'use client';

import { ChangeEvent } from 'react';
import { PatternFormat, OnValueChange } from 'react-number-format';
import TextInput, { TextInputProps } from '@/components/input/TextInput';

interface PatternInputProps extends Omit<TextInputProps, 'type'> {
  type?: 'password' | 'tel' | 'text' | undefined;

  /** Format pattern, e.g. "##/##/####", "(###) ###-####", "####-####-####" */
  format: string;

  /** Mask character for empty slots, e.g. "_" */
  mask?: string;

  /** Allow showing mask even when value is empty */
  allowEmptyFormatting?: boolean;

  patternChar?: string;
}

const PatternInput = ({
                        type = 'text',
                        format,
                        mask = '_',
                        allowEmptyFormatting = false,
                        patternChar = '#',
                        onChange,
                        ...restProps
                      }: PatternInputProps) => {
  const valueChangeHandler: OnValueChange = (
    patternFormatValues,
    sourceInfo
  ) => {
    const newChangeEvent = sourceInfo.event as
      | ChangeEvent<HTMLInputElement>
      | undefined;

    if (newChangeEvent) {
      newChangeEvent.target.value = patternFormatValues.value;

      onChange?.(newChangeEvent);
    }
  };

  return (
    <PatternFormat
      type={type}
      format={format}
      mask={mask}
      allowEmptyFormatting={allowEmptyFormatting}
      patternChar={patternChar}
      customInput={TextInput}
      onValueChange={valueChangeHandler}
      {...restProps}
    />
  );
};

export default PatternInput;
