import React from 'react';
import {View} from 'react-native';
import {Typography} from '@components/_core/Typography';
import {commonStyles} from '@shared/styles';
import {useTheme} from '@shared/theme';

import {useInputColors} from '../../hooks/useInputColors';
import {INPUT_ICONS} from '../../constants';
import {InputCoreProps} from '../../interfaces';
import {styles} from './styles';

export function InputHelper({
  helper,
  helperNumberOfLines,
  inputLength,
  inputMaxLength,
  disabled,
  focused,
  isError,
  isSuccess,
}: InputCoreProps) {
  const {iconSizes} = useTheme();
  const {helperColor} = useInputColors({
    isError,
    isSuccess,
    disabled,
    focused,
  });
  const HelperIcon = isSuccess
    ? INPUT_ICONS.success
    : isError && !focused
    ? INPUT_ICONS.error
    : null;
  const helperTexts = Array.isArray(helper) ? helper : [helper];
  const showCounter = inputLength !== undefined && inputMaxLength !== undefined;
  const ellipsizeMode = helperNumberOfLines === 1 ? 'tail' : undefined;

  return helper || showCounter ? (
    <View style={styles.row}>
      {!!helper && (
        <View style={commonStyles.flex}>
          {helperTexts.map(element => (
            <View key={element} style={styles.row}>
              {!!HelperIcon && (
                <HelperIcon color={helperColor} size={iconSizes.x4} />
              )}
              <Typography
                color={helperColor}
                numberOfLines={helperNumberOfLines}
                ellipsizeMode={ellipsizeMode}
                style={[
                  styles.helperTextContainer,
                  helperNumberOfLines === 1 && styles.singleLineHelperText,
                ]}>
                {element}
              </Typography>
            </View>
          ))}
        </View>
      )}
      {showCounter && (
        <Typography color={helperColor}>
          {inputLength}/{inputMaxLength}
        </Typography>
      )}
    </View>
  ) : null;
}
