// @flow
import React, { Component } from 'react';
import { StyleSheet, View } from 'react-native';
import styles from './ListItem.styles';
import ListItemText from './ListItemText';
import ListItemLeft from './ListItemLeft';
import ListItemRight from './ListItemRight';
import Ripple from '../Utils/Ripple';

type Props = {
  button: boolean,
  dense: boolean,
  avatar?: {
    imageUrl: string,
    description: string,
  },
  icon?: string,
  primaryText: string,
  secondaryText: string,
};

type State = {
  threeLine: boolean,
};

class ListItem extends Component<Props, State> {
  static defaultProps = {
    button: false,
    dense: false,
    primaryText: '',
    secondaryText: '',
  }

  state = {
    threeLine: false,
  }

  detectThreeLine = ({ nativeEvent: { layout: { height } } }: any) => {
    if (height > 20) {
      this.setState({ threeLine: true });
    }
  }

  render() {
    const { button, dense, avatar, icon, primaryText, secondaryText } = this.props;
    const { threeLine } = this.state;
    const singleLine = primaryText && !secondaryText;
    const twoLine = primaryText && secondaryText;
    const listStyle = StyleSheet.flatten([
      styles.listItem,
      singleLine && styles.singleLine,
      twoLine && styles.twoLine,
      threeLine && styles.threeLine,
      singleLine && dense && styles.singleLineDense,
      twoLine && dense && styles.twoLineDense,
      threeLine && dense && styles.threeLineDense,
      avatar && styles.withAvatar,
      avatar && dense && styles.withAvatarDense,
    ]);

    const parts = (
      <View style={listStyle} accessibilityRole="listitem">
        {(!!avatar || !!icon) && <ListItemLeft avatar={avatar} icon={icon} />}
        <ListItemText
          dense={dense}
          onLayout={this.detectThreeLine}
          primaryText={primaryText}
          secondaryText={secondaryText}
        />
        {(!!avatar && !!icon) && <ListItemRight icon={icon} />}
      </View>
    );

    return !button ? parts : <Ripple>{parts}</Ripple>;
  }
}

export default ListItem;
