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

import { Chip } from '~/components/chip/chip';
import { LineBehind } from '~/components/line-behind';
import { Text } from '~/components/text';
import { getTxOrText } from '~/i18n';
import { Presets } from '~/theme';
import { getElement } from '~/utils/object';
import { enhanceViewStyle } from '~/utils/styles';

import { ChipsGridProps } from './chips-grid.props';
import { ChipsGridStyles as styles } from './chips-grid.styles';

/**
 * Component that shows a grid of chips.
 *
 * @param {Presets} preset Optional type of presets.
 * @param {string} chips Optional text to display if not using `tx` or nested components.
 * @param {string} chips Optional text key which is looked up via i18n.
 * @param {string} chipsTxOptions Optional options to pass to i18n.
 * @param {string} title Optional title to display if not using `tx` or nested components.
 * @param {string} titleTx Optional title key which is looked up via i18n.
 * @param {ViewStyle} style Optional style override for the root view.
 * @param {ViewStyle} chipStyle Optional style override for the chip view.
 */
export const ChipsGrid: React.FC<ChipsGridProps> = (props) => {
  const {
    preset,
    chips,
    chipsTx,
    chipsTxOptions,
    noFill,
    title,
    titleTx,
    style,
    chipStyle: chipStyleOverride,
  } = props;
  const hasTitle = titleTx || title;
  const chipStyle = enhanceViewStyle([styles.chip, chipStyleOverride]);
  return (
    <View style={style}>
      {hasTitle && (
        <LineBehind style={styles.line}>
          <Text preset="caption" style={styles.title} text={title} tx={titleTx} />
        </LineBehind>
      )}
      <View style={styles.content}>
        {getTxOrText(chips, chipsTx, chipsTxOptions).map((tag, index) => (
          <Chip
            key={index}
            noFill={noFill}
            preset={getElement<Presets>(preset, index)}
            style={chipStyle}
            text={tag.text}
            tx={tag.tx}
          />
        ))}
      </View>
    </View>
  );
};

ChipsGrid.defaultProps = {
  preset: 'primary',
  noFill: false,
};
