import * as React from 'react';
import { View } from 'react-native';

import { Icon, IconType } from '~/components/icon';
import { Text } from '~/components/text';
import { enhanceViewStyle } from '~/utils/styles';

import { TextWithIconProps as Props } from './text-with-icon.props';
import { iconSpace, Side, TextWithIconStyles as styles } from './text-with-icon.styles';

/**
 * Helper function to get the icon component.
 *
 * @param {IconType} icons Icon list.
 */
function getIconList(icons: IconType[], side: Side) {
  return icons.map((icon, index) => (
    <Icon
      key={`${icon.name}-${index}`}
      color={icon.color}
      name={icon.name}
      size={icon.size}
      style={iconSpace[side]}
    />
  ));
}

/**
 * Helper component to display an icon besides a text.
 *
 * @param {IconType} leftIcons Array of objects representing the left icons.
 * @param {IconType} rightIcons Array of objects representing the right icons.
 * @param {string} text Optional main text.
 * @param {TextPresets} textPreset Optional text preset.
 * @param {TranslationKey} tx Optional text key which is looked up via i18n.
 * @param {object} txOptions Optional text options to pass to i18n.
 * @param {ViewStyle} style Optional style override for the root view.
 * @param {ViewStyle} leftIconStyle Optional style override for the left icon.
 * @param {ViewStyle} rightIconStyle Optional style override for the right icon.
 * @param {TextStyle} textStyle Optional style override for the main text.
 */
export const TextWithIcon: React.FC<Props> = (props) => {
  const {
    leftIcons,
    rightIcons,
    text,
    textPreset,
    tx,
    txOptions,
    style: styleOverride,
    leftIconStyle,
    rightIconStyle,
    textStyle,
  } = props;
  const style = enhanceViewStyle([styles.container, styleOverride]);
  const leftIconsStyle = enhanceViewStyle([styles.leftIcons, leftIconStyle]);
  const rightIconsStyle = enhanceViewStyle([styles.rightIcons, rightIconStyle]);
  const leftIconList = getIconList(leftIcons, 'left');
  const rightIconList = getIconList(rightIcons, 'right');

  return (
    <View style={style}>
      <View style={leftIconsStyle}>{leftIconList}</View>
      <Text preset={textPreset} style={textStyle} text={text} tx={tx} txOptions={txOptions} />
      <View style={rightIconsStyle}>{rightIconList}</View>
    </View>
  );
};

TextWithIcon.defaultProps = {
  leftIcons: [],
  rightIcons: [],
  textPreset: 'body1',
};
