Sherlock / app / (auth) / signupPassword.tsx
signupPassword.tsx
Raw
import { StyleSheet, Text, TextInputProps, View } from 'react-native'
import React, { Component, ComponentProps, createRef, useRef } from 'react'
import { SafeAreaView } from 'react-native-safe-area-context'
import { globalStyles } from '../../constants/styles';
import { Alert, AlertIcon, AlertText, ArrowRightIcon, Button, ButtonIcon, ButtonText, CloseCircleIcon, EyeIcon, EyeOffIcon, HStack, Heading, Input, InputField, InputIcon, InputSlot, KeyboardAvoidingView, VStack, set } from '@gluestack-ui/themed';
import  Colors  from '../../constants/Colors';
import { router, useLocalSearchParams } from 'expo-router';
import { Auth } from 'aws-amplify';
import { useForm, Controller } from "react-hook-form";
import validateEmail from '../../components/validateEmail';
import  { alert } from '../../components/alert';
import WelcomeInput from '../../components/welcomeInput';
import { TextInput } from 'react-native-gesture-handler';

type Params = {
  email: string;
};

// function generateRandomPassword(length:number=8) {
//   let password ="";
//   let charset = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
//   let num = '0123456789';

//   for (let i = 0; i < length; i+=2) {
//     password += charset.charAt(Math.floor(Math.random() * charset.length));
//     password += num.charAt(Math.floor(Math.random() * num.length));
//   }

//   console.log("generated password: ", password)
//   return password;
// }

const signupPassword = () => {
  const { email } = useLocalSearchParams<Params>();
  const [password, setPassword] = React.useState('');
  const [confirmPassword, setConfirmPassword] = React.useState('');
  const [showAlert, setShowAlert] = React.useState(false);
  const [isValid, setIsValid] = React.useState(false);
  const [isLoading, setIsLoading] = React.useState(false);
  const [alertMessage, setAlertMessage] = React.useState("The email you entered is not a valid email address. Please try again.");
  const [showPassword, setShowPassword] = React.useState(false);
  // const confirmPassRef = useRef<TextInputProps | null>(null);
  let confirmPassRef = createRef<TextInput>();


  async function signUp(username: string, email: string, password: string) {
    try {
      const { user } = await Auth.signUp({
        username,
        password,
        attributes: {
          email,
          'name': 'Nameless Pleb',
        },
        autoSignIn: {
          enabled: true,
        },
      });
      console.log(user);
      setIsLoading(false);
      router.push({
        pathname: "/verifyEmail",
        params: { email: email },
      });
    } catch (error) {
      console.log("error signing up:", error);
      setIsLoading(false);
      if (error instanceof Error) {
        setAlertMessage(error.message);
      } else {
        setAlertMessage("An unknown error occurred. Please try again.");
      } 
      setShowAlert(true);
    }
  }

  async function onSubmit() {
      console.log("Email: ", email);
      if(password !== confirmPassword){
        setAlertMessage("Passwords do not match. Please try again.");
        setShowAlert(true);
        return;
      }
      setIsLoading(true);
      setShowAlert(false);
      const user = await signUp(email, email,password);
  }

  function handleEye(){
    setShowPassword((showState) => {
      return !showState;
    });
  }

  return (
    <KeyboardAvoidingView style={globalStyles.container}>
      <SafeAreaView style={{ flex: 1, justifyContent: "space-between" }}>
        <VStack style={{ flex: 1 }}>
          <Heading
            size="2xl"
            style={[globalStyles.heading, styles.headingUpdate]}
          >
            How about a password?
          </Heading>

          <HStack space="sm" style={{ flexDirection: "row" }}>
            <View style={globalStyles.welcomePassContainter}>
              {/* <Input borderWidth={0} size="xl" style={globalStyles.welcomeInput}>
              <InputField
                fontSize={25}
                maxLength={20}
                style={globalStyles.welcomeInput}
                placeholder="Your Password"
                scrollEnabled={false}
                fontWeight="bold"
                type={showPassword ? "text" : "password"}
                color={Colors["dark"].redText}
                placeholderTextColor={Colors["dark"].redText}
                cursorColor={Colors["dark"].redText}
                onChangeText={(text) => {
                  setPassword(text);
                }}
                autoFocus={true}
                numberOfLines={1}
                returnKeyType="next"
                blurOnSubmit={false}
                onSubmitEditing={() => {
                  if (
                    confirmPassRef !== null &&
                    confirmPassRef.current !== null
                  ) {
                    confirmPassRef.current.focus();
                  }
                }}
              />
              <InputSlot onPress={handleEye}>
                <InputIcon as={showPassword ? EyeIcon : EyeOffIcon} />
              </InputSlot>
            </Input> */}

              <WelcomeInput
                maxLength={20}
                type={showPassword ? "text" : "password"}
                placeholder="Your Password"
                onChangeText={(text) => {
                  setPassword(text);
                }}
                autoFocus={true}
                numberOfLines={1}
                // backgroundColor='white'
                returnKeyType="next"
                blurOnSubmit={false}
                onSubmitEditing={() => {
                  if (
                    confirmPassRef !== null &&
                    confirmPassRef.current !== null
                  ) {
                    confirmPassRef.current.focus();
                  }
                }}
              >
                {/* <InputSlot onPress={handleEye}>
                <InputIcon as={EyeIcon} />
              </InputSlot> */}
              </WelcomeInput>
            </View>
            <Button
              onPress={handleEye}
              size="xl"
              maxWidth="10%"
              // style={globalStyles.welcomePassButton}
              bg={Colors.dark.background}
              style={globalStyles.eyeButton}
            >
              <ButtonIcon style={{ alignSelf: "flex-start" }} as={EyeIcon} />
            </Button>
          </HStack>

          <Heading
            size="2xl"
            style={[globalStyles.heading, styles.headingUpdate]}
          >
            Confirm Password plz
          </Heading>

          {/* <Input borderWidth={0} size="xl" style={globalStyles.welcomeInput}>
            <InputField
              fontSize={25}
              maxLength={20}
              style={globalStyles.welcomeInput}
              placeholder="Confirm it here"
              scrollEnabled={false}
              fontWeight="bold"
              type={showPassword ? "text" : "password"}
              color={Colors["dark"].redText}
              placeholderTextColor={Colors["dark"].redText}
              cursorColor={Colors["dark"].redText}
              autoFocus={true}
              numberOfLines={1}
              ref={confirmPassRef}
              returnKeyType="next"
              blurOnSubmit={false}
              onChangeText={(text) => {
                setConfirmPassword(text);
                if (password) {
                  setIsValid(true);
                }
              }}
            />
            <InputSlot onPress={handleEye}>
              <InputIcon as={showPassword ? EyeIcon : EyeOffIcon} />
            </InputSlot>
          </Input> */}

          <HStack space="sm" style={{ flexDirection: "row" }}>
            <View style={globalStyles.welcomePassContainter}>
              <WelcomeInput
                maxLength={20}
                type={showPassword ? "text" : "password"}
                placeholder="Confirm it here"
                returnKeyType="next"
                ref={confirmPassRef}
                // getRef={(input: React.MutableRefObject<null>)=>confirmPassRef = input}
                onChangeText={(text) => {
                  setConfirmPassword(text);
                  if (password) {
                    setIsValid(true);
                  }
                }}
              />
            </View>

            <Button
              onPress={handleEye}
              size="xl"
              maxWidth="10%"
              // style={globalStyles.welcomePassButton}
              bg={Colors.dark.background}
              style={globalStyles.eyeButton}
            >
              <ButtonIcon style={{ alignSelf: "flex-start" }} as={EyeIcon} />
            </Button>
          </HStack>

          {showAlert && (
            <Alert
              action="error"
              margin={5}
              marginTop={10}
              borderColor={Colors["dark"].red}
              backgroundColor={Colors["dark"].alertBackground}
              borderWidth={1}
              borderRadius={10}
              padding={5}
              width="100%"
            >
              <HStack>
                <AlertIcon
                  color={Colors["dark"].red}
                  padding={5}
                  as={CloseCircleIcon}
                  size="xl"
                  mr="$3"
                  mx="$2.5"
                />
                <AlertText color={Colors["dark"].text} padding={5}>
                  {alertMessage}
                </AlertText>
              </HStack>
            </Alert>
          )}
        </VStack>

        <VStack>
          <Button
            style={globalStyles.bottomButton}
            borderRadius={30}
            isDisabled={!isValid}
            size="xl"
            bg="#4fb2ab"
            sx={{
              ":active": {
                bg: "#00ACB5D5",
              },
            }}
            onPress={() => {
              onSubmit();
            }}
          >
            {isLoading ? (
              <ButtonText flex={1}>Registering...</ButtonText>
            ) : (
              <ButtonText flex={1}>Continue</ButtonText>
            )}

            <ButtonIcon size="xl" as={ArrowRightIcon} />
          </Button>
        </VStack>
      </SafeAreaView>
    </KeyboardAvoidingView>
  );
}

export default signupPassword

const styles = StyleSheet.create({
	headingUpdate:{
    marginLeft:0,
    paddingLeft:0,
  },
  fineTune:{
    padding:5,
    width:300,
    alignSelf:'center',
    textAlign:'center',
    marginBottom:10,
  },

})