Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
8.4 kB
2
Indexable
Never

import React, { Dispatch, SetStateAction, useEffect, useState } from 'react';
import { Alert, Image, ScrollView, StyleSheet, View, Platform } from 'react-native';
import { Button, Header, Loader, Text, Touchable } from '../../../../components';
import { colors, fonts, screenHeight, screenWidth } from '../../../../helpers/styles';
import { ICON_NAMES } from '../../../../helpers/constants/icons';
import formatter from '../../../../utils/formatter';
import { useAppSelector } from '../../../../hooks/store';
import { getActiveSubscription } from '../../../../reducer/auth/AuthSlice';
import Modal from 'react-native-modal';
import FastImage from 'react-native-fast-image';
import { IMAGE_NAMES } from '../../../../helpers/constants/images';
import * as RNIap from 'react-native-iap';

const itemSkus = ['valamonthly'];

const SubscriptionPlanView = ({
	loader,
	options,
	price,
	includedFeatures,
	popupVisible,
	setPopupVisible,
	goToHome,
	handleBuySubscription
}: {
	loader: boolean;
	options: string[];
	price: number[];
	includedFeatures: number[][];
	popupVisible: boolean;
	setPopupVisible: Dispatch<SetStateAction<boolean>>;
	goToHome: () => void;
	handleBuySubscription: (val: number) => void;
}) => {
	const [selected, setSelected] = useState(1);
	const subscription = useAppSelector(getActiveSubscription);

	useEffect(() => {
		const initIAP = async () => {
			try {
				const init = await RNIap.initConnection();
				console.log('init', init);
				const products = await RNIap.getProducts({ skus: itemSkus });
				console.log('Available products', products);
			} catch (err) {
				console.error('IAP init error', err);
				Alert.alert('Error', 'Failed to initialize in-app purchases.');
			}
		};

		initIAP();

		return () => {
			RNIap.endConnection();
		};
	}, []);

	const requestPurchase = async (sku: string) => {
		try {
			await RNIap.requestSubscription(sku);
		} catch (err) {
			console.error('Purchase error', err);
			Alert.alert('Purchase Error', 'Failed to complete the purchase. Please try again.');
		}
	};

	const handleBuyPlan = () => {
		Alert.alert('Hold on!', 'Are you sure you want to avail this offer?', [
			{
				text: 'Cancel',
				onPress: () => { }
			},
			{
				text: 'Yes',
				onPress: () => {
					if (Platform.OS === 'ios') {
						if (selected === 0) {
						requestPurchase('valamonthly'); // Use the requestPurchase function for iOS
						}
					} else {
						handleBuySubscription(selected); // Use existing handleBuySubscription for Android
					}
				}
			},
		]);
	};

	const features = [
		'Enhanced Budget Tools',
		'Link Bank Accounts',
		'Advanced Security',
		'Track Spending Habits',
		'Graphs and Charts',
		'Savings jar to visually watch the progress',
		'Recommendations and Analytics',
		'Educational Tips',
		'Savings Goals',
		'Round-Up Savings to Achieve Goals',
		'With No Ads',
		'Notifications',
		'Reward Points',
		'Dive deep into budgets',
		'Bill Reminders',
		'Multiplier to Accelerate Goals',
		'Manual ACH transfers between the external accounts',
		'Auto ACH transfers between the external accounts'
	];

	const Features = (title: string, index: number) => {
		return (
			<View style={{ flexDirection: 'row', alignItems: 'flex-start', marginVertical: 10 }}>
				<View>
					<Image
						source={includedFeatures[selected].includes(index + 1) ? ICON_NAMES.check : ICON_NAMES.cross}
						tintColor={
							includedFeatures[selected].includes(index + 1) ? colors.white : 'rgba(255, 255, 255, 0.6)'
						}
						style={{ height: 15, width: 15, marginRight: 10, top: 5 }}
						resizeMode='contain'
					/>
				</View>
				<View>
					<Text
						color={
							includedFeatures[selected].includes(index + 1) ? colors.white : 'rgba(255, 255, 255, 0.6)'
						}
						fontSize={14}
					>
						{title}
					</Text>
				</View>
			</View>
		);
	};

	if (includedFeatures?.length && options?.length) {
		return (
			<View style={{ flex: 1 }}>
				<Header title='App Offerings' />
				<Loader loading={loader} />
				<ScrollView
					contentContainerStyle={{ flexGrow: 1, paddingHorizontal: 15 }}
					showsVerticalScrollIndicator={false}
				>
					<View style={styles.tabContainer}>
						{options?.map((item, index) => (
							<Touchable
								key={index}
								onPress={() => setSelected(index)}
								style={[
									styles.tab,
									selected === index ? { backgroundColor: colors.primary } : undefined
								]}
							>
								<Text
									color={colors.darkGreen}
									fontSize={14}
									fontFamily={selected === index ? fonts.BOLD : fonts.REGULAR}
								>
									{item}
								</Text>
							</Touchable>
						))}
					</View>
					<View style={styles.card}>
						<View style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center' }}>
							<View>
								<Text fontSize={20} color={colors.white} fontFamily={fonts.BOLD}>
									{`${options[selected]}  ${selected === 2 ? '(Coming Soon)' : ''}`}
								</Text>
							</View>
							{selected === 1 ? (
								<View style={styles.tag}>
									<Text fontSize={13}>Popular</Text>
								</View>
							) : null}
						</View>
						<View style={{ marginVertical: 10, flexDirection: 'row', alignItems: 'flex-end' }}>
							<Text color={colors.white} fontSize={53} fontFamily={fonts.BOLD}>
								{`$ ${formatter.NumberFormat(price?.length ? parseFloat(`${price[selected]}`) : 0)}`}
							</Text>
							<Text color={'rgba(255, 255, 255, 0.4)'} fontSize={14} customStyle={{ bottom: 5 }}>
								/ Month
							</Text>
						</View>
						<View style={{ paddingBottom: 20, borderBottomWidth: 1, borderColor: colors.white }}>
							<Text customStyle={{ lineHeight: 30 }} fontSize={14} color={colors.white}>
								It is a long established fact that a reader will be distracted by the readable
							</Text>
						</View>
						<View style={{ paddingTop: 20 }}>
							{features?.map((item, index) => (
								<View key={index}>{Features(item, index)}</View>
							))}
						</View>
						{!options?.[selected]?.includes(subscription?.name || undefined) ? (
							<View style={{ marginVertical: 20 }}>
								<Touchable
									onPress={() => (selected !== 2 ? handleBuyPlan() : undefined)}
									style={styles.button}
								>
									<Text fontSize={14} color={'#36A3B6'} fontFamily={fonts.BOLD}>
										{selected === 2 ? 'Coming Soon' : 'Avail Now'}
									</Text>
								</Touchable>
							</View>
						) : null}
					</View>
				</ScrollView>
				<Modal isVisible={popupVisible} style={{ margin: 0 }} backdropColor={colors.white} backdropOpacity={1}>
					<View style={{ padding: 20 }}>
						<FastImage
							source={IMAGE_NAMES.subscription}
							style={{ height: screenHeight / 3 }}
							resizeMode='contain'
						/>
						<Text
							customStyle={{ textAlign: 'center', marginTop: 10 }}
							fontSize={14}
							color={colors.textGrey}
						>
							You can now utilize this Vala service
						</Text>
						<View style={{ marginVertical: 25 }}>
							<Button value='Back to Home' onPress={goToHome} />
						</View>
						<Touchable
							onPress={() => setPopupVisible(false)}
							style={{ borderBottomWidth: 1, alignSelf: 'center' }}
						>
							<Text fontSize={12} color={colors.addressGrey} customStyle={{ textAlign: 'center' }}>
								CLOSE
							</Text>
						</Touchable>
					</View>
				</Modal>
			</View>
		);
	} else if (loader) {
		return (
			<View style={{ flex: 1 }}>
				<Header title='App Offerings' />
				<Loader loading={true} />
			</View>
		);
	} else {
		return (
			<View style={{ flex: 1 }}>
				<Text>Some error occurred</Text>
			</View>
		);
	}
};

const styles = StyleSheet.create({
	tabContainer: {
		flexDirection: 'row',
		justifyContent: 'space-between',
		backgroundColor: colors.iceberg,
		borderRadius: 30,
		marginVertical: 20
	},
	tab: {
		width: '33%',
		alignItems: 'center',
		backgroundColor: colors.iceberg,
		padding: 15,
		borderRadius: 30
	},
	button: {
		backgroundColor: colors.white,
		alignSelf: 'center',
		paddingVertical: 15,
		paddingHorizontal: screenWidth / 4,
		borderRadius: 10
	},
	tag: {
		backgroundColor: colors.white,
		paddingVertical: 2,
		paddingHorizontal: 15,
		borderRadius: 5
	},
	card: {
		backgroundColor: '#36A3B5',
		borderRadius: 20,
		paddingVertical: 30,
		paddingHorizontal: 25,
		marginVertical: 10
	}
});

export default SubscriptionPlanView;
Leave a Comment