import _ from 'lodash';
import moment from 'moment';
import React from 'react';
import {
	StyleSheet,
	View,
	TouchableOpacity,
	Dimensions,
	Image,
} from 'react-native';
import FastImage from 'react-native-fast-image';
import { PaginationScroll, InfiniteScroll } from '~comp';
import { Image as NixplayImage, NixplayIcon, Text, color, transparentize } from 'nixplay-ui-kit';
import PropTypes from 'prop-types';

import { ifIphoneX } from 'react-native-iphone-x-helper';
import { debounceWrapper } from '~/lib/utils';
import { CONTENT_PAGE_SIZE } from '~/store/contentsConstants';

const { width: screenWidth } = Dimensions.get('window');
const thumbHeight = screenWidth / 3;

const styles = StyleSheet.create({
	container: {
		...ifIphoneX({
			paddingBottom: 34,
		}, {
			paddingBottom: 30,
		}),
	},
	thumbContainer: {
		flex: 1 / 3,
		aspectRatio: 1,
	},
	thumb: {
		flex: 1,
		margin: 1,
	},
	videoIconContainer: {
		position: 'absolute',
		bottom: 4,
		left: 4,
		backgroundColor: transparentize(color.white, 20),
		paddingHorizontal: 8,
		paddingVertical: 2,
		borderRadius: 8,
		flexDirection: 'row',
		alignItems: 'center',
	},
	videoDuration: {
		marginLeft: 4,
	},
	selectedIcon: {
		position: 'absolute',
		top: 4,
		right: 4,
		width: 24,
		height: 24,
		borderRadius: 12,
		backgroundColor: color.white,
		shadowOffset: { width: 0, height: 1 },
		shadowColor: color.black,
		shadowOpacity: 0.2,
		shadowRadius: 2,
		elevation: 1,
	},
});

const videoDuration = (seconds) => {
	const duration = moment.duration(seconds, 'seconds');
	return `${_.padStart(duration.minutes(), 2, 0)}:${_.padStart(duration.seconds(), 2, 0)}`;
};

const TouchableOpacityEx = debounceWrapper(TouchableOpacity);

export const PhotosGrid = (props) => {
	const ScrollComponent = props.asyncData && !props.pagination ? InfiniteScroll : PaginationScroll;
	const { contentContainerStyle, ...others } = props;
	return (
		<ScrollComponent
			{...others}
			contentContainerStyle={[styles.container, props.contentContainerStyle]}
			removeClippedSubviews
			numColumns={3}
			numPerPage={CONTENT_PAGE_SIZE}
			keyExtractor={(photo) => `${photo.id}`}
			getItemLayout={(data, index) => (
				{ length: thumbHeight, offset: thumbHeight * index, index }
			)}
			extraData={props.selectedContent}
			renderItem={({ item: photo, index, moveStart }) => {
				const disabled = !props.itemSelectable(photo);
				const photoUrl = (!_.isEmpty(photo.microThumbnailUrl) && photo.microThumbnailUrl.indexOf('MICRO_THUMBNAIL') >= 1) ? photo.microThumbnailUrl : photo.thumbnailUrl;
				return (
					<TouchableOpacityEx
						activeOpacity={0.7}
						disabled={disabled}
						style={styles.thumbContainer}
						onPress={() => props.onPressContent(photo.id, index)}
						onLongPress={(e) => props.onLongPressContent(photo.id, index, e, moveStart)}
						testID={`thumb${index}`}
					>
						{
							(_.has(photo, 'thumbnailUrl')) ? (<NixplayImage
								source={{
									uri: photo.thumbnailUrl.includes('dropbox') ? decodeURIComponent(photo.thumbnailUrl) : photoUrl,
									priority: FastImage.priority.low,
								}}
								style={styles.thumb}
								transform={[{
									rotate: `${photo.rotation}deg`,
								}]}
								resizeMode="cover"
								withProgress
							/>) : (<Image source={{ uri: photo.uri }} style={styles.thumb} resizeMode="cover" />)
						}
						{!_.isEmpty(photo.videoUrl) &&
							<View style={styles.videoIconContainer}>
								<NixplayIcon
									name="video-solid"
									color="textGrey"
									size={12}
								/>
								<Text
									textStyle="caption2"
									color="textGrey"
									style={styles.videoDuration}
								>
									{videoDuration(photo.videoDuration)}
								</Text>
							</View>
						}
						{
							disabled &&
							<View
								style={{
									position: 'absolute',
									top: 0,
									bottom: 0,
									right: 0,
									left: 0,
									backgroundColor: transparentize(color.white, 20),
								}}
							/>
						}
						{props.selectMode && props.selectedContent.indexOf(photo.id) >= 0 &&
							<View style={styles.selectedIcon}>
								<NixplayIcon
									name="checkbox-circle-on"
									color="blue"
								/>
							</View>
						}
					</TouchableOpacityEx>
				);
			}}
		/>
	);
};

PhotosGrid.propTypes = {
	asyncData: PropTypes.bool,
	pagination: PropTypes.bool,
	data: PropTypes.array,
	onPressContent: PropTypes.func,
	onLongPressContent: PropTypes.func,
	selectMode: PropTypes.bool,
	selectedContent: PropTypes.array,
	itemSelectable: PropTypes.func,
	contentContainerStyle: PropTypes.any,
};

PhotosGrid.defaultProps = {
	asyncData: false,
	pagination: false,
	data: [],
	onPressContent: () => {},
	onLongPressContent: () => {},
	selectMode: false,
	selectedContent: [],
	itemSelectable: () => true,
	contentContainerStyle: {},
};
