import i18n from '@config/i18n';
import {
  FULL_FORMAT_ES_DECIMAL_REGEX,
  FULL_FORMAT_EN_DECIMAL_REGEX,
} from '@shared/regexs';

const DECIMAL_NUMBERS = 2;

export const formatNumber = (value?: string, withDecimals = true) => {
  const defaultValue = withDecimals
    ? `0${(0.1).toLocaleString(i18n.language).replace(/\d/g, '')[0]}00` // 0,00 or 0.00 depending on the language
    : '0';
  if (!!value && isValidInput(value)) {
    const locale = i18n.language === 'es' ? 'es-AR' : i18n.language;
    return parseFloat(value.replace(/,/g, '.')).toLocaleString(locale, {
      minimumFractionDigits: withDecimals ? DECIMAL_NUMBERS : 0,
      maximumFractionDigits: withDecimals ? DECIMAL_NUMBERS : 0,
    });
  }
  return value || defaultValue;
};

export const isValidInput = (input: string) =>
  FULL_FORMAT_ES_DECIMAL_REGEX.test(input.replace(/./g, '')) ||
  FULL_FORMAT_EN_DECIMAL_REGEX.test(input.replace(/,/g, ''));

export const limitDecimals = (input: string, withDecimals = true): string => {
  if (!withDecimals || !input) {
    return input;
  }

  const decimalSeparator = (0.1)
    .toLocaleString(i18n.language)
    .replace(/\d/g, '')[0];
  const lastDecimalIndex = input.lastIndexOf(decimalSeparator);
  if (lastDecimalIndex === -1) {
    return input;
  }

  const integerPart = input.substring(0, lastDecimalIndex);
  const decimalPart = input.substring(lastDecimalIndex + 1);

  if (decimalPart.length > DECIMAL_NUMBERS) {
    return `${integerPart}${decimalSeparator}${decimalPart.slice(
      0,
      DECIMAL_NUMBERS,
    )}`;
  }

  return input;
};
