import FormInputClassic from '@material-hu/components/design-system/Inputs/Classic/form';
import { getThousandSeparator, getDecimalSeparator } from 'src/utils/form';
import { useLokaliseTranslation } from 'src/utils/i18n';

export type FloatInputProps = {
  name: string;
  required?: boolean;
  lang: string;
};

export const transformIntegerInput = (
  value: string,
  thousandSeparator: string,
  decimalSeparator: string,
) => {
  if (!value) return value;

  const escapeRegex = (str: string) =>
    str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');

  const escapedThousand = escapeRegex(thousandSeparator);
  const escapedDecimal = escapeRegex(decimalSeparator);

  // First, remove thousand separators
  const thousandRegex = new RegExp(escapedThousand, 'g');
  let cleaned = value.replace(thousandRegex, '');

  // Remove any invalid characters (keep only digits and decimal separator)
  const validCharsRegex = new RegExp(`[^0-9${escapedDecimal}]`, 'g');
  cleaned = cleaned.replace(validCharsRegex, '');

  // Ensure only one decimal separator exists
  const decimalRegex = new RegExp(escapedDecimal, 'g');
  const matches = cleaned.match(decimalRegex);

  if (matches && matches.length > 1) {
    const separatorIndex = cleaned.indexOf(decimalSeparator);
    const beforeSeparator = cleaned.substring(0, separatorIndex);
    const afterSeparator = cleaned
      .substring(separatorIndex + 1)
      .replace(decimalRegex, '');
    cleaned = beforeSeparator + decimalSeparator + afterSeparator;
  }

  return cleaned;
};

export const FloatInput = ({ name, required, lang }: FloatInputProps) => {
  const { t } = useLokaliseTranslation('service_management');
  const thousandSeparator = getThousandSeparator(lang);
  const decimalSeparator = getDecimalSeparator(lang);

  return (
    <FormInputClassic
      name={name}
      rules={{ required }}
      inputProps={{
        disabled: false,
        step: 0.01,
        inputMode: 'decimal',
        autoComplete: 'off',
        autoCorrect: 'off',
        hasCounter: false,
        errorText: t('empty_field_error'),
        placeholder: lang === 'en' ? '0.00' : '0,00',
        transform: {
          input: (value: string) =>
            transformIntegerInput(value, thousandSeparator, decimalSeparator),
        },
      }}
    />
  );
};

export default FloatInput;
