Untitled

 avatar
unknown
typescript
2 years ago
9.9 kB
5
Indexable
import React, {useCallback, useEffect, useMemo} from 'react';
import {
  BackHandler,
  Image,
  ImageBackground,
  Platform,
  ScrollView,
  StyleSheet,
  Text,
  UIManager,
  View,
} from 'react-native';

import {
  CommonActions,
  useFocusEffect,
  useNavigationState,
} from '@react-navigation/native';

import transferIcon from '@assets/crypto/transferIcon.webp';
import invest from '@assets/icons/invest.webp';
import withdraw from '@assets/icons/withdraw.webp';
import mail from '@assets/profile/mail.webp';
import {Button} from '@components/Atom';
import {sizes, spacing, typographics} from '@design-system';
import {useLocale} from '@hooks/global/useLocale';
import {useTheme} from '@hooks/global/useTheme';
import useUserInfo from '@hooks/global/useUserInfo';
import useSegmentAnalytics from '@hooks/local/useSegmentAnalytics';
import KycStep from '@models/KycStep';
import {AppParamList, AppStackProps} from '@navigator/AppParamList';
import {resolveImageSource} from '@utils/imageUtils';
import {getBottomSpace} from '@utils/iPhoneXHelpers';

if (
  Platform.OS === 'android' &&
  UIManager.setLayoutAnimationEnabledExperimental
) {
  UIManager.setLayoutAnimationEnabledExperimental(true);
}

const KYCEmailVerified: React.FC<AppStackProps<'KYCEmailVerified'>> = ({
  navigation,
  route,
}) => {
  const {translate: t} = useLocale();
  const {colors: colorTheme, images: imagesTheme} = useTheme();
  const styles = useMemo(() => getStyles(colorTheme), [colorTheme]);
  const [, useUserInfoAPI] = useUserInfo(
    _ => undefined,
    action => action.useUserInfoAPI,
  );
  const [userInfo, updateUserInfo] = useUserInfo(
    state => state.userInfo,
    action => action.updateUserInfo,
  );
  const {trackEvent, trackScreen} = useSegmentAnalytics('KYCEmailVerifiedPage');

  useEffect(() => {
    trackScreen();
  }, [trackScreen]);

  const itemList = useMemo(() => {
    return [
      {
        icon: invest,
        text: t('kyc.email_verified.label_invest'),
      },
      {
        icon: transferIcon,
        text: t('kyc.email_verified.label_transfer'),
      },
      {
        icon: withdraw,
        text: t('kyc.email_verified.label_withdraw'),
      },
    ];
  }, [t]);

  const {fetchUserInfoData} = useUserInfoAPI();

  const navigationState = useNavigationState(state => state);

  const handleButtonBackPress = useCallback(() => {
    // force not able back with physical button
    return true;
  }, []);

  useEffect(() => {
    const backHandler = BackHandler.addEventListener(
      'hardwareBackPress',
      handleButtonBackPress,
    );
    return () => {
      backHandler.remove();
    };
  }, [handleButtonBackPress]);

  const prevPage: keyof AppParamList | undefined = useMemo(() => {
    const {index, routes} = navigationState;
    if (routes) {
      return routes[index - 1]?.name as keyof AppParamList;
    }
    return undefined;
  }, [navigationState]);

  const onPress = useCallback(async () => {
    const stateNav = navigation.getState();
    const removedKycRoutes = stateNav?.routes?.filter(
      kycRoute => kycRoute?.params?.flow !== 'KYC',
    );

    const initialChangeEmailRoute =
      removedKycRoutes[removedKycRoutes.length - 1]?.name;

    const isEmailNotYetVerified =
      userInfo?.kycStatus !== 'NOT_STARTED' &&
      userInfo?.email &&
      userInfo?.kycStep !== KycStep.START;

    if (isEmailNotYetVerified) {
      return navigation.dispatch(state => {
        const {routes} = state;

        let filterRoutes = routes.filter(
          _route => _route?.params?.flow !== 'KYC',
        );

        switch (initialChangeEmailRoute) {
          case 'AccountInformation':
            filterRoutes[filterRoutes.length - 1] = {
              key: 'AccountInformation',
              name: 'AccountInformation',
              params: {
                toastTextSuccess: t('personal_page.success_change_email'),
              },
            };
            break;
          case 'AccountVerification':
            filterRoutes[filterRoutes.length - 1] = {
              key: 'AccountVerification',
              name: 'AccountVerification',
              params: {
                isShouldOpenModal: true,
              },
            };
            break;
          case 'ProfileEdit':
            filterRoutes[filterRoutes.length - 1] = {
              key: 'ProfileEdit',
              name: 'ProfileEdit',
            };
            break;
          default:
            break;
        }

        return CommonActions.reset({
          ...navigationState,
          routes: filterRoutes,
          index: filterRoutes.length - 1,
        });
      });
    }

    // ONLY NAVIGATE TO KYC TnC WHEN EMAIL VERIFICATION PROCESSED IN KYC STEP
    if (
      userInfo?.kycStatus === 'ON_PROGRESS' &&
      userInfo.email &&
      (userInfo?.kycStep === KycStep.EMAIL_VERIFIED || KycStep.START)
    ) {
      trackEvent('KYCEmailVerifiedNextTapped');
      navigation.navigate('KYCKtpOption', {
        flow: 'KYC',
        completion: route.params.completion,
      });
    } else if (
      userInfo?.kycStatus === 'ON_PROGRESS' &&
      userInfo.email &&
      userInfo?.kycStep === KycStep.EMAIL_VERIFIED &&
      userInfo.employmentStatus
    ) {
      trackEvent('KYCEmailVerifiedNextTapped');
      updateUserInfo({
        ...userInfo,
        kycStep: KycStep.EMPLOYMENT_FILLED,
      });
      navigation.navigate('KYCTermsConditions', {
        flow: 'KYC',
        completion: route.params.completion,
      });
    } else {
      // VERIFICATION DONE FROM PROFILE WITHOUT KILL APPS / OUT FROM PROFILE EDIT
      if (prevPage === 'ChangeEmail' || prevPage === 'KYCVerifyEmail') {
        return navigation.dispatch(state => {
          const {routes} = state;
          // TAKE OUT KycEmailVerified, AccountUpdateVerifyEmail, and ProfileEdit
          const filterRoutes = routes.filter(
            pages =>
              pages.name !== 'AccountUpdateVerifyEmail' &&
              pages.name !== 'KYCEmailVerified' &&
              pages.name !== 'KYCVerifyEmail' &&
              pages.name !== 'ChangeEmail',
          );
          // BACK TO PROFILE OVERVIEW
          return CommonActions.reset({
            ...navigationState,
            routes: filterRoutes,
            index: filterRoutes.length - 1,
          });
        });
      }
      return navigation.goBack();
    }
  }, [
    userInfo,
    trackEvent,
    navigation,
    route.params.completion,
    updateUserInfo,
    t,
    navigationState,
    prevPage,
  ]);

  useFocusEffect(
    useCallback(() => {
      fetchUserInfoData();
      // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []),
  );

  return (
    <ScrollView style={styles.container}>
      <View style={styles.subContainer}>
        <ImageBackground
          source={resolveImageSource(imagesTheme.bubbleEffect)}
          style={styles.imageBg}
          resizeMode="cover">
          <Image source={mail} style={styles.image} />
        </ImageBackground>
        <View style={styles.bodyBox}>
          <View>
            <View style={styles.headerBox}>
              <Text style={styles.title}>{t('kyc.email_verified.title')}</Text>
              <Text style={styles.subtitle}>
                {t('kyc.email_verified.subtitle')}
              </Text>
            </View>
            <View style={styles.itemListBox}>
              {itemList.map((item, index) => (
                <View key={index} style={styles.itemBox}>
                  <Image
                    resizeMode={'contain'}
                    source={resolveImageSource(item.icon)}
                    style={styles.itemIcon}
                  />
                  <Text style={styles.itemText}>{item.text}</Text>
                </View>
              ))}
            </View>
          </View>
        </View>
        <Button
          containerStyle={styles.button}
          type="primary-revert"
          text={t('kyc.email_verified.button')}
          onPress={onPress}
        />
      </View>
    </ScrollView>
  );
};

export default KYCEmailVerified;

const getStyles = colors =>
  StyleSheet.create({
    container: {
      flex: 1,
      height: '100%',
      backgroundColor: colors.primary.white,
    },
    subContainer: {
      justifyContent: 'space-between',
      minHeight: sizes.heightPercentageToDP('90%'),
    },
    imageBg: {
      width: '100%',
      height: sizes.widthPercentageToDP('80%'),
      justifyContent: 'center',
    },
    image: {
      width: 180,
      height: 180,
      alignSelf: 'center',
    },
    bodyBox: {
      flex: 1,
      flexDirection: 'column',
      justifyContent: 'space-between',
      paddingBottom: spacing[3] + getBottomSpace(),
    },
    headerBox: {
      justifyContent: 'center',
      alignItems: 'center',
      paddingHorizontal: spacing[4],
    },
    title: {
      ...typographics.display,
      marginBottom: spacing[1],
      color: colors.primary.black,
    },
    subtitle: {
      ...typographics.paragraph,
      color: colors.shade.darkGrey,
      textAlign: 'center',
    },
    itemListBox: {
      alignSelf: 'center',
      marginTop: spacing[3],
      paddingHorizontal: spacing[5],
    },
    itemBox: {
      flexDirection: 'row',
      marginVertical: spacing[1],
      alignItems: 'center',
    },
    itemIcon: {
      width: 20,
      height: 20,
      tintColor: colors.product.green,
      marginRight: spacing[2],
    },
    itemText: {
      ...typographics.paragraphBold,
      color: colors.primary.black,
    },
    button: {
      marginHorizontal: spacing[2],
    },
  });
Editor is loading...
Leave a Comment