import React from 'react';
import {
	View,
	StyleSheet,
	TouchableOpacity,
	Dimensions,
	FlatList,
} from 'react-native';
import _ from 'lodash';
import { Thumbnail, Text, NixplayIcon as Icon, color } from 'nixplay-ui-kit';
import PropTypes from 'prop-types';
import { debounceWrapper } from '~/lib/utils';
import { orientationToRotation } from '~/lib/sdk/helper';

const itemLimit = 4;
const { width: screenWidth } = Dimensions.get('window');
const itemSize = screenWidth / (itemLimit + 2);

const styles = StyleSheet.create({
	container: {
		flex: 1,
	},
	mediaContainer: {
		width: itemSize,
		height: itemSize,
		aspectRatio: 1,
		margin: 3,
		/**
		 * James Kong
		 * avoid shadow warning message by setting background to container
		 * */
		backgroundColor: color.white,
		borderRadius: 4,
		shadowColor: 'black',
		shadowOpacity: 0.2,
		shadowRadius: 2,
		shadowOffset: { x: 0, y: 0 },
	},
	thumbnail: {
		flex: 1,
		borderRadius: 4,
		overflow: 'hidden',
	},
	overflowIndicator: {
		flex: 1,
		backgroundColor: 'rgba(0,0,0,0.5)',
		position: 'absolute',
		alignSelf: 'center',
		alignItems: 'center',
		justifyContent: 'center',
		top: 0,
		right: 0,
		left: 0,
		bottom: 0,
		borderRadius: 4,
		overflow: 'hidden',
	},
	videoHintContainer: {
		flex: 1,
		backgroundColor: 'rgba(255,255,255,0.87)',
		borderRadius: 16,
		position: 'absolute',
		bottom: 0,
		left: 0,
		paddingRight: 8,
		paddingLeft: 8,
		paddingBottom: 3,
		paddingTop: 3,
		margin: 4,
		shadowColor: 'black',
		shadowOffset: { x: 0, y: 2 },
		shadowRadius: 4,
		shadowOpacity: 0.3,
	},
	errorBg: {
		flex: 1,
		alignItems: 'center',
		justifyContent: 'center',
		backgroundColor: color.mistBlue01,
	},
});

export const MediaRow = (props) => {
	const filteredData = _.dropRight(props.data.map((media, index) => ({
		url: media.url,
		rotation: orientationToRotation(media.orientation)
			? orientationToRotation(media.orientation).rotation
			: 0,
		photo: props.photos[index],
		index,
	})), props.data.length - itemLimit);
	const TouchableOpacityEx = debounceWrapper(TouchableOpacity);

	function isMediaDeleted(url) {
		return _.endsWith(url, '.DELETED');
	}

	const { uuid } = props;

	return (
		<FlatList
			getData={() => {}}
			data={filteredData}
			refreshing={false}
			contentContainerStyle={styles.container}
			numColumns={itemLimit}
			numPerPage={itemLimit}
			keyExtractor={(media) => `${media.url}`}
			getItemLayout={(data, index) => (
				{ length: itemSize, offset: itemSize * index, index }
			)}
			renderItem={({ item, index }) => (
				<TouchableOpacityEx
					activeOpacity={0.7}
					style={styles.mediaContainer}
					onPress={() =>
						props.onOpenMedia(index)
					}
				>
					{!isMediaDeleted(item.photo) &&
					<Thumbnail
						style={styles.thumbnail}
						source={{ uri: `${item.url}&random=${uuid}` }}
						resizeMode="cover"
						fadeDuration={1000}
						transform={[{
							rotate: `${item.rotation}deg`,
						}]}
					/>
					}
					{isMediaDeleted(item.photo) &&
					<View style={styles.errorBg} >
						<Icon name="photo-broken" testID="PhotoBroken" color="mistBlue03" />
					</View>
					}
					{index === itemLimit - 1 && props.data.length - itemLimit > 0 &&
					<View
						style={styles.overflowIndicator}
					>
						<Text
							numberOfLines={1}
							textStyle="body"
							color="white"
						>
							{(props.data.length + 1) - itemLimit}+
						</Text>
					</View>
					}
					{props.mediaKeys && props.mediaKeys.length > index &&
					!_.isEmpty(props.mediaKeys[index]) &&
					_.startsWith(props.mediaKeys[index], 'video:', 0) &&
					<View style={styles.videoHintContainer}>
						<Icon
							name="video-solid"
							color="grey04"
							size={16}
						/>
					</View>
					}
				</TouchableOpacityEx>
			)}
		/>
	);
};


MediaRow.propTypes = {
	data: PropTypes.array,
	photos: PropTypes.array,
	mediaKeys: PropTypes.array,
	onOpenMedia: PropTypes.func,
	uuid: PropTypes.string,
};

MediaRow.defaultProps = {
	data: [],
	photos: [],
	mediaKeys: [],
	onOpenMedia: () => {},
	uuid: '',
};
