import React, { Component } from "react";
import { Text } from "@plusscommunities/pluss-core-app/components";
import {
	View,
	ScrollView,
	TouchableOpacity,
	Platform,
	Linking,
	Modal,
	Dimensions,
	StyleSheet,
	ImageBackground,
} from "react-native";
import { connect } from "react-redux";
import { withSafeAreaInsets } from "react-native-safe-area-context";
import { Icon } from "@rneui/themed";
import _ from "lodash";
import { Camera } from "expo-camera";
import * as MediaLibrary from "expo-media-library";
import * as ImageManipulator from "expo-image-manipulator";
import * as ImagePicker from "expo-image-picker";
import ImageBrowser from "./expo-image-picker-multiple/ImageBrowser";
import ExpoImageManipulator from "./react-native-expo-image-cropper/ExpoImageManipulator";
import Header from "./Header";
import { Popup } from "./Popup";
import { PopupMenu } from "./PopupMenu";
import { InlineButton } from "./InlineButton";
import { getValueOrDefault, getThumb300, isVideo } from "../helper";
import {
	getMainBrandingColourFromState,
	BOXGREY,
	INACTIVE_BUTTON,
	TEXT_BLUEGREY,
	TEXT_DARK,
	LINEGREY,
} from "../colours";
import Config from "../config";
import { fileActions } from "../apis";
import { stockImagesLoaded, imageLibraryLoaded } from "../actions";

const SCREEN_WIDTH = Dimensions.get("window").width;
const SCREEN_HEIGHT = Dimensions.get("window").height;
const DEFAULT_ASPECT = [1, 1];
const DEFAULT_ALLOWS_EDITING = true;
const DEFAULT_ALLOWS_IOS_CAMERA_EDITING = false;
const DEFAULT_EXIF = true;
const DEFULAT_IMAGE_TYPE = "jpeg";
const DEFAULT_IMAGE_NAME = "image";
const DEFAULT_VIDEO_NAME = "video";
const DEFAULT_SIZE = {
	width: 1400,
};
const DEFAULT_COMPRESSION = 0.8;

class ImageUploader extends Component {
	constructor(props) {
		super(props);

		this.state = {
			showUploadMenu: false,
			warning: null,
			showPhotos: false,
			showRemote: false,
			selected: [],
			selectedType: "",
			onAttach: null,
			selectedAlbumId: "",
			showSelectAlbum: false,
			showCropper: false,
			localAlbums: [],
			loadingLocalFolders: false,
			loadingRemoteFolders: false,
		};
	}

	componentDidMount() {
		this.loadLocalAlbums();
		this.loadRemoteAlbums();
	}

	loadLocalAlbums = async () => {
		const hasPermission = await MediaLibrary.getPermissionsAsync();
		if (!hasPermission.granted) return;

		this.setState({ loadingLocalFolders: true }, async () => {
			try {
				const localAlbums = await MediaLibrary.getAlbumsAsync({
					includeSmartAlbums: true,
				});
				this.setState({
					loadingLocalFolders: false,
					localAlbums: [
						{
							title: "All Photos",
							id: "",
						},
						...localAlbums,
					],
				});
			} catch (error) {
				console.log("loadLocalAlbums - error", error);
				this.setState({ loadingLocalFolders: false });
			}
		});
	};

	loadRemoteAlbums = () => {
		this.setState({ loadingRemoteFolders: true }, async () => {
			try {
				const stockImages = await fileActions.getStockPhotos();
				this.props.stockImagesLoaded(stockImages);
				const libraryRes = await fileActions.getMediaFolders(
					this.props.user.site,
				);
				this.props.imageLibraryLoaded(libraryRes.data);
			} catch (error) {
				console.log("loadRemoteAlbums - error", error);
			} finally {
				this.setState({ loadingRemoteFolders: false });
			}
		});
	};

	showUploadMenu() {
		this.setState({
			showUploadMenu: true,
		});
	}

	hideUploadMenu() {
		this.setState({
			showUploadMenu: false,
		});
	}

	retryUpload = async (mediaUri, uploadUri) => {
		try {
			const uri = isVideo(uploadUri)
				? mediaUri
				: (await this.resizeImageAsync(mediaUri)).uri;
			const res = await fileActions.uploadUserMediaWithProgress(
				uri,
				uploadUri,
				(progress) => {
					if (this.props.onUploadProgress)
						this.props.onUploadProgress(progress);
				},
			);
			this.props.onUploadSuccess(
				Config.env.baseUploadsUrl + res.key,
				uploadUri,
			);
			console.log("upload(retry) success", Config.env.baseUploadsUrl + res.key);
		} catch (e) {
			console.log("retryUpload error", e);
			this.props.onUploadFailed(uploadUri);
		}
	};

	resizeImageAsync = async (uri) => {
		const actions = [
			{
				resize: getValueOrDefault(this.props.size, DEFAULT_SIZE),
			},
		];
		const saveOptions = {
			format: DEFULAT_IMAGE_TYPE,
			compress: getValueOrDefault(this.props.quality, DEFAULT_COMPRESSION),
			base64: true,
		};
		return await ImageManipulator.manipulateAsync(uri, actions, saveOptions);
	};

	handleImagePicked = async (imageUri) => {
		let uploadUri;
		try {
			const fileName = `${getValueOrDefault(this.props.fileName, DEFAULT_IMAGE_NAME)}.${DEFULAT_IMAGE_TYPE}`;
			uploadUri = fileActions.getUploadUrl(this.props.userId, fileName);

			this.props.onUploadStarted(uploadUri, imageUri);
			this.hideUploadMenu();

			const resized = await this.resizeImageAsync(imageUri);
			if (this.props.onlySelectImage) {
				this.props.onImageSelected(resized, fileName);
				return;
			}

			const res = await fileActions.uploadUserMediaWithProgress(
				resized.uri,
				uploadUri,
				(progress) => {
					if (this.props.onUploadProgress)
						this.props.onUploadProgress(progress);
				},
			);

			this.props.onUploadSuccess(
				Config.env.baseUploadsUrl + res.key,
				uploadUri,
			);
			console.log("upload success", Config.env.baseUploadsUrl + res.key);
		} catch (e) {
			console.log("handleImagePicked error", e);
			this.props.onUploadFailed(uploadUri);
		}
	};

	handleMultiImagePicked = async (imagesSelected) => {
		// Signal start of all images selected
		const imagesUploaded = imagesSelected.map((image) => {
			const fileName = `${getValueOrDefault(this.props.fileName, DEFAULT_IMAGE_NAME)}.${DEFULAT_IMAGE_TYPE}`;
			const uploadUri = fileActions.getUploadUrl(this.props.userId, fileName);
			if (!this.props.onlySelectImage)
				this.props.onUploadStarted(uploadUri, image.uri);
			return { imageUri: image.uri, uploadUri, fileName };
		});
		this.hideUploadMenu();

		// Sequentially upload all imagesUploaded
		for (let i = 0; i < imagesUploaded.length; i++) {
			const image = imagesUploaded[i];
			const { imageUri, uploadUri, fileName } = image;
			try {
				const resized = await this.resizeImageAsync(imageUri);
				if (this.props.onlySelectImage) {
					this.props.onImageSelected(resized, fileName);
					return;
				}

				const res = await fileActions.uploadUserMediaWithProgress(
					resized.uri,
					uploadUri,
					(progress) => {
						if (this.props.onUploadProgress)
							this.props.onUploadProgress(progress);
					},
				);
				this.props.onUploadSuccess(
					Config.env.baseUploadsUrl + res.key,
					uploadUri,
				);
				console.log("upload success", Config.env.baseUploadsUrl + res.key);
			} catch (e) {
				console.log("handleMultiImagePicked error", e);
				this.props.onUploadFailed(uploadUri);
			}
		}
	};

	handleVideoPicked = async (uri) => {
		let uploadUri;
		try {
			const fileType = uri.substring(uri.lastIndexOf(".") + 1);
			const fileName = `${getValueOrDefault(this.props.fileName, DEFAULT_VIDEO_NAME)}.${fileType}`;
			uploadUri = fileActions.getUploadUrl(this.props.userId, fileName);

			this.props.onUploadStarted(uploadUri, uri);
			this.hideUploadMenu();

			const res = await fileActions.uploadUserMediaWithProgress(
				uri,
				uploadUri,
				(progress) => {
					if (this.props.onUploadProgress)
						this.props.onUploadProgress(progress);
				},
			);

			this.props.onUploadSuccess(
				Config.env.baseUploadsUrl + res.key,
				uploadUri,
			);
			console.log("upload success", Config.env.baseUploadsUrl + res.key);
		} catch (e) {
			console.log("handleVideoPicked error", e);
			this.props.onUploadFailed(uploadUri);
		}
	};

	showWarningPopup(camera, roll) {
		if (Platform.OS !== "ios") {
			return;
		}
		let innerWarning = "";
		if (camera && roll) {
			innerWarning = "both your camera and photo library";
		} else if (camera) {
			innerWarning = "your camera";
		} else if (roll) {
			innerWarning = "your photo library";
		} else {
			// nothing to warn about
			return;
		}
		this.setState({
			warning: `You must grant access to ${innerWarning}. Tap Go to settings to change your permission settings.`,
		});
	}

	closeWarningPopup() {
		this.setState({
			warning: null,
		});
	}

	goToPermissionSettings() {
		Linking.openURL("app-settings:");
		this.setState({
			warning: null,
		});
	}

	askPermissionsAsync = async () => {
		const cameraPermission = await Camera.requestCameraPermissionsAsync();
		const rollPermission = await MediaLibrary.requestPermissionsAsync();
		if (
			cameraPermission.status !== "granted" ||
			(Platform.OS === "ios" && rollPermission.status !== "granted")
		) {
			this.showWarningPopup(
				cameraPermission.status !== "granted",
				rollPermission.status !== "granted",
			);
			return false;
		}
		if (this.state.localAlbums?.length <= 0) this.loadLocalAlbums();

		return true;
	};

	isEditingEnabled = () => {
		return (
			!this.props.multiple &&
			!this.props.allowVideo &&
			getValueOrDefault(this.props.allowsEditing, DEFAULT_ALLOWS_EDITING)
		);
	};

	openCamera = async () => {
		if (!(await this.askPermissionsAsync())) return;

		let editingAllowed = this.isEditingEnabled();
		if (Platform.OS === "ios") {
			editingAllowed = getValueOrDefault(
				this.props.allowsEditingIOSCamera,
				getValueOrDefault(
					this.props.allowsEditing,
					DEFAULT_ALLOWS_IOS_CAMERA_EDITING,
				),
			);
		}
		const result = await ImagePicker.launchCameraAsync({
			allowsEditing: editingAllowed,
			aspect: getValueOrDefault(this.props.aspect, DEFAULT_ASPECT),
			exif: getValueOrDefault(this.props.exif, DEFAULT_EXIF),
		});

		if (!result.canceled && !_.isEmpty(result.assets)) {
			this.handleImagePicked(result.assets[0].uri);
		}
	};

	openVideoCamera = async () => {
		if (!(await this.askPermissionsAsync())) return;

		const result = await ImagePicker.launchCameraAsync({
			allowsEditing: this.isEditingEnabled(),
			mediaTypes: ImagePicker.MediaTypeOptions.Videos,
		});

		if (!result.canceled && !_.isEmpty(result.assets)) {
			this.handleImagePicked(result.assets[0].uri);
		}
	};

	openLibrary = async () => {
		this.setState(
			{
				showUploadMenu: false,
			},
			() => {
				setTimeout(() => {
					this.setState({
						showPhotos: true,
						selected: [],
						showRemote: true,
						selectedAlbumId: "",
					});
				}, 1000);
			},
		);
	};

	openPhotos = async () => {
		if (Platform.OS === "android") {
			const multiple = !!this.props.multiple;
			const result = await ImagePicker.launchImageLibraryAsync({
				allowsEditing: this.isEditingEnabled(),
				allowsMultipleSelection: multiple,
				...(multiple && {
					selectionLimit: getValueOrDefault(this.props.imagesLimit, 10),
				}),
				aspect: getValueOrDefault(this.props.aspect, DEFAULT_ASPECT),
				exif: getValueOrDefault(this.props.exif, DEFAULT_EXIF),
				mediaTypes: this.props.allowVideo
					? ImagePicker.MediaTypeOptions.All
					: ImagePicker.MediaTypeOptions.Images,
			});
			if (!(result.canceled || result.cancelled) && !_.isEmpty(result.assets)) {
				if (result.assets.length === 1 && result.assets[0].type === "video") {
					this.handleVideoPicked(result.assets[0].uri);
				} else {
					this.handleMultiImagePicked(result.assets);
				}
			}
			return;
		}

		// iOS behaviour
		if (!(await this.askPermissionsAsync())) return;

		this.setState(
			{
				showUploadMenu: false,
			},
			() => {
				setTimeout(() => {
					this.setState({
						showPhotos: true,
						selected: [],
						showRemote: false,
						selectedAlbumId: "",
					});
				}, 1000);
			},
		);
	};

	hidePhotos = () => {
		this.setState({ showPhotos: false });
	};

	openCropper = () => {
		// Switching modals - requires a timeout to ensure the modal is closed before opening the next one
		this.setState(
			{
				showPhotos: false,
			},
			() => {
				setTimeout(() => {
					this.setState({
						showCropper: true,
					});
				}, 1000);
			},
		);
	};

	toggleCropper = () => {
		this.setState({ showCropper: !this.state.showCropper });
	};

	onSelectAlbum = () => {
		this.setState({ showSelectAlbum: true });
	};

	onSelectAlbumClosed = () => {
		this.setState({ showSelectAlbum: false });
	};

	onAlbumSelected = (selectedAlbumId) => {
		this.setState({ showSelectAlbum: false, selectedAlbumId });
	};

	onSelectionChange = (selected, videoSelected, onAttach) => {
		this.setState({
			selected,
			selectedType: videoSelected ? "video" : "image",
			onAttach,
		});
	};

	onSelected = async (callback) => {
		if (this.isEditingEnabled()) {
			this.openCropper();
		} else {
			const mediaSelected = await callback;
			// console.log('mediaSelected', mediaSelected);
			if (this.state.showRemote) {
				if (this.props.onLibrarySelected) {
					mediaSelected.map((media) => {
						this.props.onLibrarySelected(media.uri);
					});
				}
			} else {
				if (mediaSelected[0].mediaType === MediaLibrary.MediaType.video) {
					const uri = mediaSelected[0].localUri || mediaSelected[0].uri;
					this.handleVideoPicked(uri);
				} else {
					this.handleMultiImagePicked(mediaSelected);
				}
			}

			this.hidePhotos();
		}
	};

	onRemoveImage = (uri) => {
		const selected = [...this.state.selected];
		const deleteIndex = selected.indexOf(uri);
		selected.splice(deleteIndex, 1);
		this.setState({ selected });
	};

	buildOptions = () => {
		const options = [
			{
				text: "Take photo",
				onPress: this.openCamera,
			},
		];
		if (this.props.allowVideo)
			options.push({
				text: "Record video",
				onPress: this.openVideoCamera,
			});
		options.push({
			text: "Camera Roll",
			onPress: this.openPhotos,
		});
		if (!this.props.hideLibrary)
			options.push({
				text: "Image Library",
				onPress: this.openLibrary,
			});

		return options;
	};

	renderSelectionPreview() {
		const { selected, showRemote } = this.state;

		return (
			<View>
				<ScrollView
					horizontal
					showsHorizontalScrollIndicator={false}
					contentContainerStyle={styles.selectionPreviewContainer}
				>
					{selected &&
						selected.map((uri) => {
							const imageUri = showRemote ? getThumb300(uri) : uri;
							return (
								<View key={uri} style={styles.previewItemContainer}>
									<ImageBackground
										style={styles.previewItemImage}
										source={{ uri: imageUri }}
									/>
									<TouchableOpacity
										style={styles.previewItemRemoveButton}
										onPress={() => this.onRemoveImage(uri)}
									>
										<View
											style={[
												styles.previewItemRemoveContainer,
												{ backgroundColor: this.props.colourBrandingMain },
											]}
										>
											<Icon
												name="times"
												type="font-awesome"
												iconStyle={styles.previewItemRemoveIcon}
											/>
										</View>
									</TouchableOpacity>
								</View>
							);
						})}
				</ScrollView>
			</View>
		);
	}

	renderSelectedAlbum() {
		const { localAlbums, selectedAlbumId, showRemote } = this.state;
		const selectedAlbum = (
			showRemote ? this.props.imageLibrary : localAlbums
		).find((album) => album.id === selectedAlbumId);
		const selectedAlbumText = selectedAlbum ? selectedAlbum.title : "";

		return (
			<TouchableOpacity onPress={this.onSelectAlbum}>
				<View style={styles.selectAlbumButton}>
					<Text style={styles.selectAlbumButtonText}>{selectedAlbumText}</Text>
					<Icon
						name="angle-down"
						type="font-awesome"
						iconStyle={styles.selectAlbumButtonIcon}
					/>
				</View>
			</TouchableOpacity>
		);
	}

	renderSelectedComponent = (selectedItemNumber) => {
		return (
			<View style={styles.selectedItemContainer}>
				<View
					style={[
						styles.selectedMarkerContainer,
						{ backgroundColor: this.props.colourBrandingMain },
					]}
				>
					{this.props.multiple ? (
						<Text style={styles.selectedItemText}>{selectedItemNumber}</Text>
					) : (
						<Icon
							name="check"
							type="font-awesome"
							iconStyle={styles.selectedItemIcon}
						/>
					)}
				</View>
			</View>
		);
	};

	renderBrowser() {
		const { selected, selectedAlbumId, showRemote } = this.state;
		const { imagesLimit, multiple, allowVideo, imageLibrary } = this.props;
		const width = (SCREEN_WIDTH - 10 * 2) / 4;

		return (
			<ImageBrowser
				max={!multiple ? 1 : imagesLimit}
				loadCount={30}
				onChange={this.onSelectionChange}
				renderSelectedComponent={this.renderSelectedComponent}
				callback={this.onSelected}
				selected={selected}
				allowVideo={allowVideo}
				style={styles.browserContainer}
				itemStyle={styles.itemContainer}
				itemWidth={width}
				itemHeight={width}
				album={selectedAlbumId}
				remoteAlbums={showRemote ? imageLibrary : null}
			/>
		);
	}

	renderAttachButton() {
		const { selected, selectedType } = this.state;
		const canAttach = selected.length > 0 && !_.isEmpty(selectedType);
		const attachText = `Attach ${canAttach ? selected.length : ""} ${canAttach ? selectedType : ""}${selected.length > 1 ? "s" : ""}`;
		const bottom =
			Platform.OS === "android" ? (this.props.insets?.bottom ?? 0) : 0;

		return (
			<View style={{ backgroundColor: "#fff" }}>
				<View style={styles.buttonContainer}>
					<InlineButton
						color={canAttach ? this.props.colourBrandingMain : INACTIVE_BUTTON}
						onPress={this.state.onAttach}
						fillTouchable
						large
						disabled={!canAttach}
					>
						{attachText}
					</InlineButton>
				</View>
				{bottom > 0 && <View style={{ height: bottom }} />}
			</View>
		);
	}

	renderSelectAlbumPopup() {
		const { showSelectAlbum, localAlbums, showRemote } = this.state;
		if (!showSelectAlbum) return null;

		return (
			<Modal
				visible
				transparent
				animationType="slide"
				onRequestClose={this.onSelectAlbumClosed}
			>
				<View style={styles.selectAlbumModal}>
					<View style={styles.selectAlbumContainer}>
						<View style={styles.selectAlbumTitleContainer}>
							<Text style={styles.selectAlbumTitle}>Select Album</Text>
						</View>
						<ScrollView>
							{(showRemote ? this.props.imageLibrary : localAlbums).map(
								(album, index) => {
									return (
										<TouchableOpacity
											key={album.id}
											onPress={() => this.onAlbumSelected(album.id)}
										>
											<View
												style={[
													styles.albumOptionContainer,
													index === 0 && { borderTopWidth: 0 },
												]}
											>
												<Text style={styles.albumOptionText}>
													{album.title}
												</Text>
											</View>
										</TouchableOpacity>
									);
								},
							)}
						</ScrollView>
						<TouchableOpacity onPress={this.onSelectAlbumClosed}>
							<View
								style={[
									styles.albumOptionContainer,
									{ marginHorizontal: 0 },
									Platform.OS === "android" && {
										paddingBottom: 16 + (this.props.insets?.bottom ?? 0),
									},
								]}
							>
								<Text
									style={[
										styles.albumOptionText,
										{ color: this.props.colourBrandingMain },
									]}
								>
									Cancel
								</Text>
							</View>
						</TouchableOpacity>
					</View>
				</View>
			</Modal>
		);
	}

	renderPhotos() {
		return (
			<Modal
				visible
				transparent
				animationType="slide"
				onRequestClose={this.hidePhotos}
			>
				<View style={styles.modalContainer}>
					<Header
						leftIcon="angle-left"
						onPressLeft={this.hidePhotos}
						text={this.props.popupTitle || "Attach image"}
					/>
					<View style={styles.contentContainer}>
						{this.renderSelectionPreview()}
						{this.renderSelectedAlbum()}
						{this.renderBrowser()}
					</View>
					{this.renderAttachButton()}
				</View>
				{this.renderSelectAlbumPopup()}
			</Modal>
		);
	}

	render() {
		const { warning, showUploadMenu, showPhotos, showCropper, selected } =
			this.state;

		if (warning != null) {
			return (
				<Popup
					title="Permissions missing"
					text={warning}
					options={[
						{
							text: "Go to settings",
							action: this.goToPermissionSettings.bind(this),
							bold: true,
						},
						{
							text: "Ignore",
							action: this.closeWarningPopup.bind(this),
						},
					]}
				/>
			);
		}

		if (showUploadMenu) {
			const options = this.buildOptions();
			return (
				<PopupMenu
					onClose={this.hideUploadMenu.bind(this)}
					options={options}
					title={this.props.popupTitle}
					cancelText="Cancel"
				/>
			);
		}

		if (showPhotos) return this.renderPhotos();

		if (showCropper) {
			return (
				<ExpoImageManipulator
					photo={{ uri: selected[0] }}
					onToggleModal={this.toggleCropper}
					isVisible={showCropper}
					onPictureChoosed={(data) => {
						this.handleImagePicked(data.uri);
					}}
				/>
			);
		}

		return null;
	}
}

const styles = StyleSheet.create({
	modalContainer: {
		flex: 1,
	},
	contentContainer: {
		flex: 1,
		backgroundColor: BOXGREY,
	},
	browserContainer: {
		padding: 10,
	},
	itemContainer: {
		padding: 4,
	},
	selectedItemContainer: {
		flex: 1,
		backgroundColor: "#0008",
	},
	selectedMarkerContainer: {
		position: "absolute",
		top: 6,
		right: 6,
		width: 20,
		height: 20,
		borderRadius: 10,
		alignItems: "center",
		justifyContent: "center",
	},
	selectedItemText: {
		fontFamily: "sf-semibold",
		fontSize: 12,
		color: "#fff",
		marginBottom: 1,
	},
	selectedItemIcon: {
		fontSize: 12,
		color: "#fff",
		marginBottom: 1,
	},
	buttonContainer: {
		alignItems: "center",
		justifyContent: "center",
		height: 60,
		paddingHorizontal: 14,
		backgroundColor: "#fff",
	},
	selectAlbumButton: {
		paddingTop: 13,
		paddingHorizontal: 14,
		flexDirection: "row",
		alignItems: "center",
	},
	selectAlbumButtonText: {
		fontFamily: "sf-medium",
		fontSize: 14,
		color: TEXT_BLUEGREY,
		marginRight: 6,
	},
	selectAlbumButtonIcon: {
		fontSize: 20,
		color: TEXT_BLUEGREY,
	},
	selectAlbumModal: {
		position: "absolute",
		bottom: 0,
		left: 0,
		right: 0,
		top: 0,
		backgroundColor: "rgba(0,0,0,0.5)",
		zIndex: 1000,
	},
	selectAlbumContainer: {
		position: "absolute",
		bottom: 0,
		left: 0,
		right: 0,
		backgroundColor: "#fff",
		borderTopLeftRadius: 12,
		borderTopRightRadius: 12,
		maxHeight: SCREEN_HEIGHT / 2,
	},
	selectAlbumTitleContainer: {
		padding: 16,
		borderColor: LINEGREY,
		borderBottomWidth: 1,
	},
	selectAlbumTitle: {
		fontFamily: "sf-semibold",
		fontSize: 16,
		textAlign: "center",
		color: TEXT_DARK,
	},
	albumOptionContainer: {
		marginHorizontal: 16,
		paddingVertical: 16,
		borderColor: LINEGREY,
		borderTopWidth: 1,
	},
	albumOptionText: {
		fontFamily: "sf-regular",
		fontSize: 16,
		textAlign: "center",
		color: TEXT_DARK,
	},
	selectionPreviewContainer: {
		paddingTop: 14,
		paddingRight: 2,
		paddingLeft: 14,
	},
	previewItemContainer: {
		marginRight: 12,
	},
	previewItemImage: {
		width: 50,
		height: 50,
		alignItems: "center",
		justifyContent: "center",
		borderRadius: 4,
		overflow: "hidden",
	},
	previewItemRemoveButton: {
		position: "absolute",
		top: -8,
		right: -8,
	},
	previewItemRemoveContainer: {
		justifyContent: "center",
		alignItems: "center",
		borderRadius: 10,
		width: 20,
		height: 20,
		borderWidth: 2,
		borderColor: "#fff",
	},
	previewItemRemoveIcon: {
		fontSize: 10,
		color: "#fff",
		marginBottom: 1,
	},
});

const mapStateToProps = (state) => {
	const { user, media } = state;
	const imageLibrary = media.imageLibrary
		.filter((folder) => !folder.Public)
		.map((album) => {
			return {
				title: album.Name,
				id: album.RowId || "",
				images: album.RowId ? album.Images : media.stockImages,
			};
		});

	return {
		user,
		imageLibrary,
		colourBrandingMain: getMainBrandingColourFromState(state),
	};
};

export default connect(
	mapStateToProps,
	{ stockImagesLoaded, imageLibraryLoaded },
	null,
	{ forwardRef: true },
)(withSafeAreaInsets(ImageUploader));
