'use client';

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

interface NumberInputProps extends Omit<TextInputProps, 'type'> {
  thousandSeparator?: string;
  decimalSeparator?: string;
  decimalScale?: number;
  allowNegative?: boolean;
  prefix?: string;
  suffix?: string;
  fixedDecimalScale?: boolean;
  inputPrefix?: ReactNode;
  inputSuffix?: ReactNode;
}

const NumberInput = ({
  thousandSeparator = ',',
  decimalSeparator = '.',
  decimalScale = 5,
  allowNegative = true,
  onChange,
  inputPrefix,
  inputSuffix,
  ...restProps
}: NumberInputProps) => {
  const valueChangeHandler: OnValueChange = (
    numberFormatValues,
    sourceInfo
  ) => {
    const newChangeEvent = sourceInfo.event as
      | ChangeEvent<HTMLInputElement>
      | undefined;

    if (newChangeEvent) {
      newChangeEvent.target.value = parseFloat(
        numberFormatValues.value
      ) as unknown as string;

      onChange?.(newChangeEvent);
    }
  };

  return (
    <NumericFormat
      thousandSeparator={thousandSeparator}
      decimalSeparator={decimalSeparator}
      customInput={TextInput}
      onValueChange={valueChangeHandler}
      decimalScale={decimalScale}
      allowNegative={allowNegative}
      inputPrefix={inputPrefix}
      inputSuffix={inputSuffix}
      {...restProps}
    />
  );
};

export default NumberInput;
