import React, { Component } from "react";
import { Linking } from "react-native";
import { connect } from "react-redux";
import ParsedText from "react-native-parsed-text";
import { Text } from "./Text";
import { getMainBrandingColourFromState, TEXT_DARKEST } from "../colours";
import { getValidUrl } from "../helper";
import { analyticsActions } from "../apis";

class FormattedText extends Component {
	static get UrlTextRegex() {
		return /\[([^\]\|\]]+)\|([^\]\|\]]+)\]/i;
	}

	checkLog(type, target) {
		if (this.props.logClicks) {
			analyticsActions.log(
				this.props.site,
				type,
				this.props.entityType,
				this.props.entityId,
				{ target },
			);
		}
	}

	onPressUrl = (url) => {
		const urlToUse = getValidUrl(url);
		Linking.openURL(urlToUse);
		this.checkLog("UrlClick", urlToUse);
	};

	onPressUrlText = (urlText) => {
		const texts = urlText.match(FormattedText.UrlTextRegex);
		this.onPressUrl(texts[1]);
	};

	onPressEmail = (email) => {
		Linking.openURL(`mailto:${email}`);
		this.checkLog("EmailClick", email);
	};

	onPressPhone = (phone) => {
		const parsedPhone = phone.replace(/\D/g, "");
		Linking.openURL(`tel:${parsedPhone.replace(/\D/g, "")}`);
		this.checkLog("PhoneClick", parsedPhone);
	};

	ifEnabled = (value) => (this.props.disabled ? undefined : value);

	renderTextContent(matchingString, matches) {
		return matches[1];
	}

	renderUrlText(matchingString, matches) {
		return matches[2];
	}

	render() {
		const {
			style,
			numberOfLines,
			titleSize,
			colourBrandingMain,
			subtitleSize,
			children,
		} = this.props;

		return (
			<ParsedText
				maxFontSizeMultiplier={1.2}
				style={[styles.text, this.ifEnabled({ lineHeight: 24 }), style]}
				numberOfLines={numberOfLines}
				parse={[
					{
						pattern: /\*\*(.*?)\*\*/i,
						style: this.ifEnabled({
							fontFamily: "sf-bold",
							lineHeight: 24,
						}),
						renderText: this.renderTextContent,
					},
					{
						pattern: /\*t\*(.*?)\*t\*/i,
						style: this.ifEnabled({
							fontSize: titleSize || 22,
							color: colourBrandingMain,
							fontFamily: "sf-semibold",
							lineHeight: 24,
						}),
						renderText: this.renderTextContent,
					},
					{
						pattern: /\*s\*(.*?)\*s\*/i,
						style: this.ifEnabled({
							fontSize: subtitleSize || 18,
							color: TEXT_DARKEST,
							fontFamily: "sf-semibold",
							lineHeight: 24,
						}),
						renderText: this.renderTextContent,
					},
					{
						pattern: FormattedText.UrlTextRegex,
						style: this.ifEnabled({ color: colourBrandingMain }),
						onPress: this.ifEnabled(this.onPressUrlText),
						renderText: this.renderUrlText,
					},
					{
						pattern:
							/(?:(?:https?|ftp|file):\/\/|www\.|ftp\.)(?:\([-A-Z0-9+&@#\/%=~_|$?!:,.]*\)|[-A-Z0-9+&@#\/%=~_|$?!:,.])*(?:\([-A-Z0-9+&@#\/%=~_|$?!:,.]*\)|[A-Z0-9+&@#\/%=~_|$])/im,
						style: this.ifEnabled({ color: colourBrandingMain }),
						onPress: this.ifEnabled(this.onPressUrl),
					},
					{
						pattern: /([A-Z0-9._%-]+)@([A-Z0-9.-]+\.[A-Z]{2,4})/im,
						style: this.ifEnabled({ color: colourBrandingMain }),
						onPress: this.ifEnabled(this.onPressEmail),
					},
					{
						pattern:
							/(?:\+?(\d{1,3}))?([-. (]*(\d{1,3})[-. )]*)?((\d{2,4})[-. ]*(\d{2,4})(?:[-.x ]*(\d+))?)\s*$/im,
						style: this.ifEnabled({ color: colourBrandingMain }),
						onPress: this.ifEnabled(this.onPressPhone),
					},
				]}
			>
				{children}
			</ParsedText>
		);
	}
}

const styles = {
	text: {
		color: TEXT_DARKEST,
		fontSize: 14,
		fontFamily: "sf-regular",
	},
};

const mapStateToProps = (state) => {
	return {
		colourBrandingMain: getMainBrandingColourFromState(state),
	};
};

export default connect(mapStateToProps, {})(FormattedText);
