import { forwardRef, useState } from 'react';
import { NumericFormat } from 'react-number-format';

const NumberFormatRupiah = forwardRef(function NumberFormatRupiah(props, ref) {
  const { onChange, maxValue, minValue, maxLength, minLength, allowDecimalValue, ...other } = props;
  const [newValue, setNewValue] = useState(props.value);

  const key = (e2) => {
    const kode = e2.charCode;
    if (kode === 45 && (newValue?.toString().includes('(') || newValue?.toString().includes(')'))) {
      setNewValue(`${props.value}`);
    } else if (
      kode === 45 &&
      !(newValue?.toString().includes('(') || newValue?.toString().includes(')'))
    ) {
      setNewValue(`(${props.value})`);
    }
  };

  return (
    <NumericFormat
      {...other}
      isNumericString
      onKeyPress={key}
      thousandSeparator="."
      decimalSeparator=","
      decimalScale={allowDecimalValue ? 2 : 0}
      getInputRef={ref}
      allowNegative={false}
      isAllowed={(values) => {
        const { floatValue, value } = values;

        if (floatValue > 999999999999) return false;

        if (value.includes(',') && value.split(',')[1] && value.split(',')[1].length > 2) {
          return false;
        }

        const integerPart = value.split(',')[0].replace(/^0+/, '');
        const integerDigits = integerPart.length;

        if (maxLength !== undefined && integerDigits > maxLength) return false;
        if (minLength !== undefined && integerDigits < minLength) return false;

        if (floatValue !== undefined) {
          if (maxValue !== undefined && floatValue > maxValue) return false;
          if (minValue !== undefined && floatValue < minValue) return false;
        }

        return true;
      }}
      onValueChange={(values) => {
        onChange({
          target: {
            name: props.name,
            value: values.value,
          },
        });
      }}
    />
  );
});

NumberFormatRupiah.defaultProps = {
  maxValue: undefined,
  minValue: undefined,
};

export default NumberFormatRupiah;
