import { type FC } from 'react';
import { useFormContext } from 'react-hook-form';

import FormInputClassic from '@material-hu/components/design-system/Inputs/Classic/form';

import { type InputValidations } from 'src/pages/dashboard/serviceManagement/types';
import { useLokaliseTranslation } from 'src/utils/i18n';

const MAX_INTEGER_LENGTH = 21;

export type IntegerInputProps = {
  name: string;
  required?: boolean;
  formFilled?: boolean;
  answerInput?: any;
  validations?: InputValidations;
};

export const IntegerInput: FC<IntegerInputProps> = ({
  name,
  required,
  validations,
  formFilled,
}) => {
  const { t } = useLokaliseTranslation(['service_management', 'validations']);

  const {
    formState: { errors },
  } = useFormContext();
  const pattern = validations?.pattern || '^[0-9]+$';

  const validationRules = {
    required: required,
    pattern: {
      value: new RegExp(pattern),
      message: t('integer_validation'),
    },
    ...(validations?.minimum && {
      min: {
        value: validations.minimum,
        message: t('minimum_validation', {
          min: validations.minimum,
        }),
      },
    }),
    ...(validations?.maximum && {
      max: {
        value: validations.maximum,
        message: t('maximum_validation', {
          max: validations.maximum,
        }),
      },
    }),
  };

  const errorMessage =
    (errors?.[name]?.message as string) || t('validations:required');

  return (
    <FormInputClassic
      name={name}
      rules={validationRules}
      inputProps={{
        step: 1,
        disabled: formFilled,
        inputMode: 'numeric',
        autoComplete: 'off',
        autoCorrect: 'off',
        hasCounter: false,
        errorText: errorMessage,
        maxLength: MAX_INTEGER_LENGTH,
        transform: {
          input: value => value?.replace(/[^0-9]/g, '') || '',
        },
        placeholder: '00',
      }}
    />
  );
};

export default IntegerInput;
