import React from 'react';
import {
  StyleSheet,
  Text,
  TouchableNativeFeedback,
  View,
} from 'react-native';
import { Conversation, Message, UserRole } from '../../models';
import { Card } from '../ui';
import { RelativeTimestamp } from './RelativeTimestamp';

interface Props {
  onPress: () => void;
  data: Conversation & { lastMessage?: Message };
  userRole: UserRole;
}

function getUserKey(userRole: UserRole) {
  return userRole === UserRole.EMPLOYEE
    ? 'employer'
    : 'employee';
}

export const ConversationItem: React.SFC<Props> = ({ data, userRole, onPress }) => (
  <Card style={{ padding: 0 }}>
    <TouchableNativeFeedback onPress={onPress} background={TouchableNativeFeedback.SelectableBackground()}>
      <View style={styles.container}>
        <View style={{flex: 7}}>
          <Text style={styles.title} numberOfLines={1}>
            {data[getUserKey(userRole)].name}
          </Text>
          {data.lastMessage && (
            <Text numberOfLines={1}>
              {data.lastMessage.body}
            </Text>
          )}
        </View>
        <View style={styles.timestampContainer}>
          {data.lastMessage && (
            <RelativeTimestamp
              timestamp={data.lastMessage.timestamp}
              style={styles.timestamp}
            />
          )}
        </View>
      </View>
    </TouchableNativeFeedback>
  </Card>
);

const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'space-between',
    padding: 16,
  },
  timestamp: {
    fontSize: 12,
  },
  timestampContainer: {
    flex: 4,
    justifyContent: 'center',
    alignItems: 'flex-end',
    marginHorizontal: 3,
  },
  title: {
    fontWeight: 'bold',
    fontSize: 16,
  },
});
