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,
    allowNegativeValue, // ambil custom prop di sini
    ...other // other sekarang TIDAK mengandung allowNegativeValue
  } = 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} // aman: other tidak punya allowNegativeValue
      // gunakan prop NumericFormat yang valid
      valueIsNumericString
      onKeyPress={key}
      thousandSeparator="."
      decimalSeparator=","
      decimalScale={allowDecimalValue ? 2 : 0}
      getInputRef={ref}
      // gunakan allowNegativeValue untuk mengatur allowNegative MUI prop
      allowNegative={Boolean(allowNegativeValue)}
      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,
  // default agar backward-compatible
  allowNegativeValue: false,
  allowDecimalValue: false,
};

export default NumberFormatRupiah;
