Sherlock / app / (auth) / login.tsx
login.tsx
Raw
import { Dimensions, StyleSheet, Text, TextInputProps, View } from "react-native";
import React, { Component, ComponentProps, createRef, useEffect, useRef } from "react";
import { SafeAreaView } from "react-native-safe-area-context";
import { globalStyles } from "../../constants/styles";
import {
  Alert,
  AlertIcon,
  AlertText,
  ArrowRightIcon,
  Button,
  ButtonIcon,
  ButtonSpinner,
  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 { 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";
import { supabase } from "../../components/supabase";
import global from "../../constants/global";
import { TouchableOpacity } from "@gorhom/bottom-sheet";
import { sendRecovery } from "../../components/authHelpers";
import { useAuth } from "../../components/authContext";


type SignInParams ={
  username:string;
  password:string;
}


const login = () => {
  const [email, setEmail] = React.useState("");
  const [password, setPassword] = React.useState("");
  const [showAlert, setShowAlert] = React.useState(false);
  const [isLoading, setIsLoading] = React.useState(false);
  const [fontSize, setFontSize] = React.useState(25);
  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 passwordRef = useRef<any>(null);
  const auth = useAuth()

  async function onSubmit() {
    // console.log("Email: ", email);
    if (validateEmail(email) === false) {
      setAlertMessage("Email is not valid. Please try again.");
      setShowAlert(true);
      return;
    }
    if(!email || !password){
      setAlertMessage("Please fill out all fields.");
      setShowAlert(true);
      return;
    }

    setIsLoading(true);
    setShowAlert(false);

    auth.signIn(email, password).then(()=>{
      router.replace('/home')
    }).catch((error)=>{
      console.log("Error signing in: ", error);
      setAlertMessage(error.message);
      setShowAlert(true);
      setIsLoading(false);
      return;
    })
  }

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

  return (
    <KeyboardAvoidingView style={styles.container}>
      <SafeAreaView style={{ flex: 1, justifyContent: "space-between" }}>
        <VStack style={{ flex: 1 }}>
          <Heading
            size="2xl"
            style={[globalStyles.heading, styles.headingUpdate]}
          >
            Can I get your email pwetty pwease?
          </Heading>

          <HStack space="sm" style={styles.inputDiv}>
              <WelcomeInput
                maxLength={50}
                type="text"
                placeholder="Your email"
                allowFontScaling={true}
                style={styles.input}
                value={email}
                onChangeText={(text) => {
                  setEmail(text);
                  if(text.length > 21){
                    if(fontSize <=18){
                      setFontSize(18)
                    }else{
                      let t = fontSize * (0.8 / (text.length - 21));
                      setFontSize(t<18 ? 18 : t);
                    }
                  }else{
                    if(fontSize !=25){
                      setFontSize(25);
                    }
                  }
                }}
                autoFocus={true}
                numberOfLines={1}
                // backgroundColor='white'
                returnKeyType="next"
                blurOnSubmit={false}
                fontSize={fontSize}
                onSubmitEditing={() => {
                  if (passwordRef !== null && passwordRef.current !== null) {
                    passwordRef.current.focus();
                  }
                }}
                
              >
                {/* <InputSlot onPress={handleEye}>
                <InputIcon as={EyeIcon} />
              </InputSlot> */}
              </WelcomeInput>
          </HStack>

          <Heading
            size="2xl"
            style={[globalStyles.heading, styles.headingUpdate]}
          >
            Now your super secret password
          </Heading>

          <HStack space="sm" style={styles.inputDiv}>
            <View style={styles.pass}>
              <WelcomeInput
                maxLength={20}
                style={styles.input}
                type={showPassword ? "text" : "password"}
                placeholder="It goes right here"
                returnKeyType="done"
                paddingRight={0}
                ref={passwordRef}
                // getRef={(input: React.MutableRefObject<null>)=>confirmPassRef = input}
                onChangeText={(text) => {
                  setPassword(text);
                }}
                onSubmitEditing={() => {
                  onSubmit();
                }}
                />
              </View>

            <Button
              onPress={handleEye}
              size="xl"
              maxWidth="10%"
              // style={globalStyles.welcomePassButton}
              style={styles.eye}
            >
              <ButtonIcon style={{ alignSelf: "center" }} as={EyeIcon} />
            </Button>
          </HStack>

          <TouchableOpacity
            style={styles.forgotPass}
            onPress={()=>{
              router.push('/(auth)/forgotPassword')
            }}
          >
            <Text style={{color:Colors.dark.link}}>
              Forgot your password?🤨
            </Text>
          </TouchableOpacity>

          {showAlert && (
            <Alert
              action="error"
              style={globalStyles.welcomeAlert}
            >
              <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}
            size="xl"
            bg="#4fb2ab"
            sx={{
              ":active": {
                bg: "#00ACB5D5",
              },
            }}
            onPress={() => {
              onSubmit();
            }}
          >
            {isLoading ? (
              <ButtonText flex={1}>Logging in...</ButtonText>
            ) : (
              <ButtonText flex={1}>Login</ButtonText>
            )}

            {isLoading&&<ButtonSpinner ml={'auto'} />}
            {!isLoading&&<ButtonIcon size="xl" as={ArrowRightIcon} />}
          </Button>
        </VStack>
      </SafeAreaView>
    </KeyboardAvoidingView>
  );
};

export default login;

const styles = StyleSheet.create({
  headingUpdate: {
    // marginLeft: 0,
    paddingLeft: 0,
  },
  input:{
    width: global.width*0.9,
    marginHorizontal:10
  },
  container:{
    flex:1,
    backgroundColor:Colors.dark.tabBg,
  },
  inputDiv:{
    flexDirection:'row',
    width: global.width*0.9,
    marginLeft:10,
  },
  eye:{
      backgroundColor:Colors.dark.tabBg,
      justifyContent:'center',
  },
  pass:{
    width: '80%',
  },
  forgotPass:{
    marginLeft:20,
    marginTop:20
  }
});