import React from 'react';
import {
	StyleSheet,
	View,
	TouchableOpacity,
} from 'react-native';
import {
	Avatar,
	NixplayIcon as Icon,
	Text,
	color,
} from 'nixplay-ui-kit';
import _ from 'lodash';
import FastImage from 'react-native-fast-image';

import i18n from '~/locale/i18n';
import PropTypes from 'prop-types';
import moment from 'moment/min/moment-with-locales';
import { debounceWrapper } from '~/lib/utils';
import { activityMessage, isOutgoingActivity } from '~/lib/activities';
import { MediaRow } from './mediaRow';

const styles = StyleSheet.create({
	container: {
		backgroundColor: 'transparent',
		flexDirection: 'column',
	},
	mainContainer: {
		flex: 1,
		marginLeft: 9,
		marginRight: 9,
		paddingTop: 4,
		paddingBottom: 4,
		flexDirection: 'row',
	},
	newMessageContainer: {
		flex: 1,
		marginTop: 16,
		marginBottom: 8,
		justifyContent: 'center',
	},
	newMessageText: {
		alignSelf: 'center',
		position: 'absolute',
		backgroundColor: 'white',
		paddingRight: 4,
		paddingLeft: 4,
	},
	newMessageLine: {
		width: '100%',
		height: 1,
		backgroundColor: color.mistBlue03,
		position: 'absolute',
		alignSelf: 'center',
	},
	avatarContainer: {
		width: 36,
		height: 36,
		position: 'relative',
		bottom: 0,
		left: 0,
		aspectRatio: 1,
		alignSelf: 'flex-end',
	},
	avatar: {
		aspectRatio: 1,
		width: 32,
		height: 32,
	},
	badge: {
		alignSelf: 'center',
	},
	avatarBadgeContainer: {
		position: 'absolute',
		right: 0,
		bottom: 0,
		width: 16,
		height: 16,
		marginRight: 4,
		alignItems: 'center',
		justifyContent: 'center',
		borderRadius: 8,
		overflow: 'hidden',
		backgroundColor: color.green,
	},
	meBadgeContainer: {
		width: 24,
		height: 24,
		alignSelf: 'flex-end',
		justifyContent: 'center',
		borderRadius: 16,
		marginLeft: 4,
		overflow: 'hidden',
	},
	contentContainer: {
		flex: 1,
		flexDirection: 'row',
		alignItems: 'stretch',
		marginTop: 5,
		marginBottom: 5,
	},
	contentColumn: {
		flex: 1,
		flexDirection: 'column',
		justifyContent: 'center',
		overflow: 'hidden',
	},
	content: {
		padding: 12,
		borderRadius: 8,
	},
	rowContainer: {
		flex: 1,
		flexDirection: 'row',
		alignItems: 'stretch',
		marginRight: 14,
	},
	rowContent: {
		flexDirection: 'row',
	},
	activityText: {
		flex: 1,
		marginRight: 4,
	},
	nameText: {
		flex: 1,
		marginRight: 4,
	},
	textContainer: {
		width: '75%',
	},
	textContent: {
		marginLeft: 4,
	},
	timeIndicator: {
		position: 'relative',
		top: 0,
		right: 0,
		marginBottom: 4,
	},
});


export const ActivityListItem = (props) => {
	const {
		activity,
		firstName,
		lastName,
		languageCode,
		onMediaItemPress,
		uuid,
		source: avatarSource,
	} = props;
	const TouchableOpacityEx = debounceWrapper(TouchableOpacity);
	function renderContent() {
		if (activity.connectionEvent || activity.deletedPhotos) {
			return (<Text textStyle="subhead" isSensitive>{activityMessage(activity)}</Text>);
		} else if (activity.mediaExchange) {
			return (
				<MediaRow
					uuid={uuid}
					getData={() => {}}
					photos={activity.mediaExchange.content.photos}
					mediaKeys={activity.mediaExchange.content.successKeys}
					data={activity.mediaExchange.content.photos.map((item, index) => ({
						url: activity.mediaExchange.content.thumbnailUrls[index],
						orientation: _.has(activity.mediaExchange.content, `metadata['${item}'].orientation`)
							? activity.mediaExchange.content.metadata[item].orientation
							: 0,
					}))}
					onOpenMedia={(index) => onMediaItemPress(activity, index, false)}
				/>
			);
		} else if (activity.comment) {
			return (
				<View style={styles.rowContent}>
					<MediaRow
						uuid={uuid}
						getData={() => {}}
						photos={[activity.comment.s3key]}
						data={[{
							url: activity.comment.photoUrl,
							orientation: _.has(activity.comment.content.metadata, `['${activity.comment.s3key}'].orientation`)
								? activity.comment.content.metadata[activity.comment.s3key].orientation
								: 0,
						}]}
						onOpenMedia={() => {
							const index = _.indexOf(activity.comment.content.photos, activity.comment.s3key);
							onMediaItemPress(activity, index, !(activity.comment.s3key.indexOf('DELETED') > -1));
						}}
					/>
					{!(activity.comment.content.photos[0].indexOf('DELETED') > -1) &&
						<View style={styles.textContainer}>
							<Text
								style={styles.textContent}
								textStyle="subhead"
								lines={2}
								isSensitive
							>
								{activityMessage(activity)}
							</Text>
						</View>}
				</View>
			);
		}
		return null;
	}

	function getTimestamp() {
		moment.locale(`${languageCode}`);
		let { timestamp } = activity;
		if (timestamp > moment().utc().valueOf()) {
			timestamp = moment().utc().valueOf() - 1;
		}
		return `${moment(timestamp).fromNow()}`;
	}

	const alignment = isOutgoingActivity(activity) ? 'flex-end' : 'flex-start';
	const contentBackgroundColor = isOutgoingActivity(activity) ? color.mistBlue02 : color.grey01;
	let badgeIcon = '';
	let badgeBackgroundColor = 'transparent';
	const leftContentMargin = isOutgoingActivity(activity) ? 35 : 0;
	const rightContentMargin = isOutgoingActivity(activity) ? 0 : 35;

	// get activity type's icon and color
	if (activity.connectionEvent) {
		badgeIcon = 'checkbox-circle-o';
		badgeBackgroundColor = color.green;
	} else if (activity.mediaExchange) {
		badgeIcon = 'photo';
		badgeBackgroundColor = color.blue;
	} else if (activity.comment) {
		badgeIcon = 'chat';
		badgeBackgroundColor = color.orange;
	} else if (activity.deletedPhotos) {
		badgeIcon = 'trash';
		badgeBackgroundColor = color.red;
	}
	// avatar filter
	const source = (_.has(avatarSource, 'uri') && avatarSource.uri !== null) ? { ...avatarSource, cache: FastImage.cacheControl.web, priority: FastImage.priority.high } : null;
	return (
		<TouchableOpacityEx
			style={styles.container}
			activeOpacity={0.7}
			onPress={() => {
				if (activity.comment) {
					const index = _.indexOf(activity.comment.content.photos, activity.comment.s3key);
					onMediaItemPress(activity, index, !(activity.comment.s3key.indexOf('DELETED') > -1));
				}
			}}
		>
			{activity.newMessage &&
			<View style={styles.newMessageContainer}>
				<View style={styles.newMessageLine} />
				<Text
					style={styles.newMessageText}
					color="grey04"
					textStyle="caption2"
				>
					{i18n.t('friends.NewMessages')}
				</Text>
			</View>
			}
			<View style={styles.mainContainer}>
				{!isOutgoingActivity(activity) &&
				<View style={styles.avatarContainer}>
					<Avatar
						style={styles.avatar}
						firstName={firstName}
						lastName={lastName}
						size="small"
						source={source}
					/>
					<View style={[styles.avatarBadgeContainer,
						{ backgroundColor: badgeBackgroundColor }]}
					>
						<Icon
							style={[styles.badge]}
							name={badgeIcon}
							testID={badgeIcon}
							color={color.white}
							size={10.67}
						/>
					</View>
				</View>
				}
				<View style={styles.contentContainer}>
					<View style={[styles.contentColumn, { alignItems: alignment }]}>
						<Text
							style={[styles.timeIndicator]}
							textStyle="description"
							textAlign="left"
							numberOfLines={1}
							color="grey03"
						>
							{isOutgoingActivity(activity) && `${i18n.t('common.me')} · `}{getTimestamp()}
						</Text>
						<View style={[styles.content,
							{
								backgroundColor: contentBackgroundColor,
								marginLeft: leftContentMargin,
								marginRight: rightContentMargin,
							}]}
						>
							{renderContent()}
						</View>
					</View>
					{isOutgoingActivity(activity) &&
					<View style={[styles.meBadgeContainer,
						{ backgroundColor: badgeBackgroundColor }]}
					>
						<Icon
							style={[styles.badge]}
							name={badgeIcon}
							testID={badgeIcon}
							color={color.white}
							size={16}
						/>
					</View>
					}
				</View>
			</View>
		</TouchableOpacityEx>
	);
};

ActivityListItem.propTypes = {
	activity: PropTypes.object.isRequired,
	firstName: PropTypes.string,
	lastName: PropTypes.string,
	onMediaItemPress: PropTypes.func,
	uuid: PropTypes.string,
	source: PropTypes.object.isRequired,
	languageCode: PropTypes.string,
};

ActivityListItem.defaultProps = {
	firstName: '',
	lastName: '',
	onMediaItemPress: () => {},
	uuid: '',
	languageCode: '',
};
