import React, { Component } from "react";
import { View, TouchableOpacity, Modal, Dimensions, Alert } from "react-native";
import { Text } from "./Text";
import { Icon } from "@rneui/themed";
import { WebView } from "react-native-webview";
import { File, Paths } from "expo-file-system";
import * as Sharing from "expo-sharing";
import { FontAwesome } from "./Icon";
import { Spinner } from "./Spinner";
import { StatusBarHeight, getFileName } from "../helper";

const SCREEN_HEIGHT = Dimensions.get("window").height;

class PDFPopup extends Component {
	state = {
		loaded: false,
	};

	onLoadStarted() {
		this.setState({
			loaded: false,
		});
	}

	onLoadEnded() {
		this.setState({
			loaded: true,
		});
	}

	onChangeIndex(index) {
		this.props.onChangeIndex(index);
	}

	getUrl() {
		const linkPrefix =
			"http://drive.google.com/viewerng/viewer?embedded=true&url=";
		return `${linkPrefix}${this.props.source}`;
	}

	download = async () => {
		try {
			const file = await File.downloadFileAsync(
				this.props.source,
				new File(Paths.document, getFileName(this.props.source)),
				{ idempotent: true },
			);
			await Sharing.shareAsync(file.uri, {
				UTI: "public.item",
			});
		} catch (error) {
			console.log("PDFPopup download error:", error);
			Alert.alert(
				"Download Failed",
				"Unable to download PDF. Please try again.",
				[{ text: "OK" }],
			);
		}
	};

	closePopup() {
		this.props.onClose();
	}

	renderFooter() {
		if (this.props.pdfCount && this.props.pdfCount === 1) {
			return null;
		}
		return (
			<View style={styles.footerContent}>
				<TouchableOpacity
					onPress={this.onChangeIndex.bind(this, -1)}
					activeOpacity={0.6}
				>
					<Icon
						type="font-awesome"
						name="angle-left"
						iconStyle={[styles.chevron]}
					/>
				</TouchableOpacity>
				<Text style={styles.footerText}>
					{this.props.selectedIndex + 1} / {this.props.pdfCount}
				</Text>
				<TouchableOpacity
					onPress={this.onChangeIndex.bind(this, 1)}
					activeOpacity={0.6}
				>
					<Icon
						type="font-awesome"
						name="angle-right"
						iconStyle={[styles.chevron]}
					/>
				</TouchableOpacity>
			</View>
		);
	}

	render() {
		if (!this.props.source) {
			return null;
		}
		return (
			<Modal
				visible={this.props.visible}
				transparent
				animationType="slide"
				onRequestClose={this.closePopup.bind(this)}
			>
				<View
					style={{
						flex: 1,
						backgroundColor: "#000",
						paddingTop: StatusBarHeight(0),
					}}
				>
					<View style={styles.headerContent}>
						<TouchableOpacity
							onPress={this.closePopup.bind(this)}
							activeOpacity={0.6}
						>
							<FontAwesome name="x" style={[styles.menuIcon]} />
						</TouchableOpacity>
						<View style={styles.titleContainer}>
							<Text style={styles.title}>{this.props.title}</Text>
						</View>
						<TouchableOpacity onPress={this.download} activeOpacity={0.6}>
							<Icon
								type="font-awesome"
								name="cloud-download"
								iconStyle={[styles.menuIcon]}
							/>
						</TouchableOpacity>
					</View>
					<View style={{ flex: 1, backgroundColor: "#fff" }}>
						{this.state.loaded ? null : (
							<Spinner
								style={{
									height: SCREEN_HEIGHT - StatusBarHeight(145),
									flex: 0,
								}}
							/>
						)}
						<WebView
							source={{
								uri: this.getUrl(),
							}}
							javaScriptEnabled
							domStorageEnabled
							originWhitelist={["*"]}
							mixedContentMode="always"
							renderError={(e) => {
								console.log("errored");
								console.log(e);
							}}
							style={[
								{
									flex: 1,
									backgroundColor: "#fff",
								},
							]}
							onLoadStart={this.onLoadStarted.bind(this)}
							onLoadEnd={this.onLoadEnded.bind(this)}
						/>
					</View>
					{this.renderFooter()}
				</View>
			</Modal>
		);
	}
}

const styles = {
	container: {
		flex: 1,
		position: "relative",
		backgroundColor: "#000",
	},
	innerContainer: {
		flex: 1,
		paddingLeft: 15,
		paddingRight: 15,
	},
	menuIcon: {
		fontSize: 25,
		padding: 15,
		width: 55,
		textAlign: "center",
		color: "#fff",
		zIndex: 3,
	},
	headerContent: {
		flexDirection: "row",
		alignItems: "center",
		height: 70,
	},
	titleContainer: {
		flex: 1,
	},
	title: {
		color: "#fff",
		fontFamily: "sf-semibold",
		fontSize: 16,
		textAlign: "center",
	},
	footerContent: {
		flexDirection: "row",
		alignItems: "center",
		justifyContent: "center",
		height: 70,
		//alignSelf: 'flex-end'
	},
	chevron: {
		fontSize: 25,
		padding: 15,
		width: 55,
		textAlign: "center",
		color: "#fff",
		zIndex: 3,
	},
	footerText: {
		fontFamily: "sf-regular",
		fontSize: 14,
		color: "#fff",
		width: 150,
		textAlign: "center",
	},
};

export { PDFPopup };
