import React from 'react';
import {
  StyleSheet,
  Text,
  TextStyle,
  View,
  ViewStyle,
} from 'react-native';
import { Message } from '../../models';
import { RelativeTimestamp } from './RelativeTimestamp';

interface Props {
  own: boolean;
  message: Message;
  foreignColor: string;
  hasTimestamp?: boolean;
}

export const MessageItem: React.SFC<Props> = ({ own, message, foreignColor, hasTimestamp }) => {

  const messageBodyStyles = {
    flexDirection: own
      ? 'row-reverse'
      : 'row',
  } as ViewStyle;
  const timestampStyle = {
    textAlign: own
      ? 'left'
      : 'right',
  } as TextStyle;
  const messageTextStyle = [styles.text, own ? styles.textLeft : styles.textRight];
  return (
    <View style={styles.container}>
      <View style={[styles.body, messageBodyStyles]}>
        <View>
          <View
            style={
              [styles.bubble, own ? styles.own : {
                backgroundColor: foreignColor,
                alignSelf: 'flex-end',
              }]}
          >
            <Text style={messageTextStyle}>
              {message.body}
            </Text>
          </View>
          {hasTimestamp && (
            <RelativeTimestamp
              timestamp={message.timestamp}
              style={StyleSheet.flatten([styles.baseTimestamp, timestampStyle])}
            />)
          }
        </View>
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flexDirection: 'column',
    marginVertical: 8,
  },
  baseTimestamp: {
    paddingHorizontal: 6,
    fontSize: 11,
  },
  body: {
    flexDirection: 'column',
    justifyContent: 'flex-end',
  } as ViewStyle,
  text: {
    color: 'white',
  },
  textLeft: {
    textAlign: 'left',
  },
  textRight: {
    textAlign: 'right',
  },
  bubble: {
    justifyContent: 'flex-start',
    alignSelf: 'flex-start',
    borderRadius: 16,
    padding: 8,
  },
  own: {
    backgroundColor: 'gray',
    alignSelf: 'flex-start',
  },
});
