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

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

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

	componentDidUpdate(prevProps) {
		const sourceChanged = prevProps.source !== this.props.source;
		const becameVisible = !prevProps.visible && this.props.visible;
		if (sourceChanged || becameVisible) {
			// Popup is reused across attachments — clear stale state so the
			// spinner reappears and any prior error from a different PDF resets.
			clearTimeout(this._loadTimeout);
			this._loadTimeout = null;
			this.setState({ loaded: false, error: false });
		}
	}

	componentWillUnmount() {
		clearTimeout(this._loadTimeout);
		this._loadTimeout = null;
	}

	onLoadStarted() {
		this.setState({
			loaded: false,
			error: false,
		});
		clearTimeout(this._loadTimeout);
		this._loadTimeout = setTimeout(() => {
			this.setState({ error: true });
		}, 15000);
	}

	onLoadEnded() {
		clearTimeout(this._loadTimeout);
		this._loadTimeout = null;
		this.setState({
			loaded: true,
		});
	}

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

	getUrl() {
		if (!this.props.source) {
			return "";
		}
		const linkPrefix =
			"https://drive.google.com/viewerng/viewer?embedded=true&url=";
		return `${linkPrefix}${encodeURIComponent(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.error ? (
							<View style={styles.errorContainer}>
								<Text style={styles.errorTitle}>Unable to load this PDF.</Text>
								<Text style={styles.errorSubtitle}>
									Try downloading it instead.
								</Text>
								<TouchableOpacity
									onPress={this.download}
									activeOpacity={0.6}
									style={styles.errorDownloadButton}
								>
									<Icon
										type="font-awesome"
										name="cloud-download"
										iconStyle={styles.errorDownloadIcon}
									/>
									<Text style={styles.errorDownloadText}>Download PDF</Text>
								</TouchableOpacity>
							</View>
						) : (
							<>
								{this.state.loaded ? null : (
									<Spinner
										style={{
											height: SCREEN_HEIGHT - StatusBarHeight(145),
											flex: 0,
										}}
									/>
								)}
								<WebView
									source={{
										uri: this.getUrl(),
									}}
									javaScriptEnabled
									domStorageEnabled
									originWhitelist={["*"]}
									renderError={() => {
										// Surface error UI in the parent View rather than the
										// default WebView error chrome. Defer setState to avoid
										// triggering a state update during another render.
										if (!this.state.error) {
											setTimeout(() => this.setState({ error: true }), 0);
										}
										return null;
									}}
									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",
	},
	errorContainer: {
		flex: 1,
		alignItems: "center",
		justifyContent: "center",
		paddingHorizontal: 32,
		paddingVertical: 24,
		backgroundColor: "#fff",
	},
	errorTitle: {
		fontFamily: "sf-semibold",
		fontSize: 18,
		color: TEXT_DARK,
		textAlign: "center",
	},
	errorSubtitle: {
		fontFamily: "sf-regular",
		fontSize: 14,
		color: TEXT_LIGHT,
		textAlign: "center",
		marginTop: 8,
	},
	errorDownloadButton: {
		flexDirection: "row",
		alignItems: "center",
		justifyContent: "center",
		marginTop: 24,
		paddingHorizontal: 20,
		paddingVertical: 12,
	},
	errorDownloadIcon: {
		fontSize: 20,
		color: TEXT_DARK,
		marginRight: 8,
	},
	errorDownloadText: {
		fontFamily: "sf-semibold",
		fontSize: 16,
		color: TEXT_DARK,
	},
};

export { PDFPopup };
