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

import { Bullet } from '~/components/bullet';
import { Icon, IconType } from '~/components/icon';
import { ListItem } from '~/components/list-item';
import { Tag } from '~/components/tag';
import { TextWithIcon } from '~/components/text-with-icon';
import { testIdProps } from '~/test/utils';

import { PackageDetailsItemProps as Props } from './package-list-item.props';
import {
  PACKAGE_ITEM_RIGHT_ICON,
  HAS_SIBLINGS_ICON,
  IN_WAREHOUSE_ICON,
  packageDetailsItemStyles as styles,
} from './package-list-item.styles';

/**
 * Show the package details as an item list.
 *
 * @param {string} barcode Package barcode.
 * @param {Preset} bulletPreset Bullet preset.
 * @param {string} currentSpace Package current space.
 * @param {boolean} hasSiblings True if belongs to multi-parcel.
 * @param {boolean} isInWarehouse True if package is in the warehouse.
 * @param {string} retailer Retailer name.
 * @param {string} routeSequence Route sequence.
 * @param {ViewStyle} style Optional style for the container.
 * @param {Function} onPress Callback function when the item is pressed.
 */
export const PackageListItem: React.FC<Props> = (props) => {
  const {
    barcode,
    bulletPreset,
    currentSpace,
    hasSiblings,
    isInWarehouse,
    retailer,
    routeSequence,
    style,
    onPress,
  } = props;
  const routeTag = routeSequence ? (
    <Tag
      key="tag-route"
      preset="primary"
      style={styles.spacer}
      text={routeSequence}
      {...testIdProps('item-tag-route')}
    />
  ) : null;
  const retailerTag = retailer ? (
    <Tag
      key="tag-retailer"
      preset="primary"
      style={styles.spacer}
      text={retailer}
      {...testIdProps('item-tag-retailer')}
    />
  ) : null;
  const spaceTag = currentSpace ? (
    <Tag key="tag-space" preset="primary" text={currentSpace} {...testIdProps('item-tag-space')} />
  ) : null;
  const subtitle = (
    <ScrollView horizontal style={styles.subtitleView} {...testIdProps('item-subtitle')}>
      {[routeTag, retailerTag, spaceTag]}
    </ScrollView>
  );
  const icons: IconType[] = [];

  isInWarehouse && icons.push(IN_WAREHOUSE_ICON);
  hasSiblings && icons.push(HAS_SIBLINGS_ICON);

  const title = <TextWithIcon rightIcons={icons} text={barcode} {...testIdProps('item-title')} />;

  function handlePress() {
    onPress(barcode);
  }

  return (
    <ListItem
      centerStyle={styles.centerView}
      leftComponent={
        <View style={styles.bulletView}>
          <Bullet preset={bulletPreset} {...testIdProps('item-bullet')} />
        </View>
      }
      rightComponent={<Icon {...PACKAGE_ITEM_RIGHT_ICON} />}
      style={style}
      subtitle={subtitle}
      title={title}
      onPress={handlePress}
    />
  );
};
