import { useNavigation } from '@react-navigation/core';
import { RouteProp } from '@react-navigation/native';
import {StackNavigationProp} from '@react-navigation/stack';
import { Input } from 'react-native-elements';
import { current } from 'immer';
import React, {useEffect, useMemo, useRef, useState} from 'react';
import {
  Alert,
  KeyboardAvoidingView,
  Platform,
  StatusBar,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
} from 'react-native';
import {
  ArrowButton,
  Background,
  BasicButton,
  // RegistrationWizard,
  TaggInput,
  TaggSquareButton,
} from '../../components';
import {emailRegex, nameRegex, passwordRegex, phoneRegex, usernameRegex} from '../../constants';
import {
  ERROR_NEXT_PAGE,
  ERROR_PHONE_IN_USE,
  ERROR_TWILIO_SERVER_ERROR,
} from '../../constants/strings';
import {OnboardingStackParams} from '../../routes';
import {sendOtpStatusCode} from '../../services';
import {BackgroundGradientType} from '../../types';
import {SCREEN_HEIGHT, SCREEN_WIDTH} from '../../utils';
import { createIconSetFromFontello } from 'react-native-vector-icons';

type RevampedOnboardingRouteProp = RouteProp<OnboardingStackParams, 'RevampedOnboarding'>;
type RevampedOnboardingNavigationProp = StackNavigationProp<
  OnboardingStackParams,
  'RevampedOnboarding'
>;
interface RevampedOnboardingProps {
  route: RevampedOnboardingRouteProp;
  navigation: RevampedOnboardingNavigationProp;
}

const RevampedOnboarding: React.FC<RevampedOnboardingProps> = ({route}) => {
    const {isPhoneVerified} = route.params;
    const navigation = useNavigation();
    type renderStatusType = 'firstName' | 'lastName' | 'username' | 'email';
    const [renderStatus, setStatus] = useState<renderStatusType>('firstName');
    const [currentStep, setCurrentStep] = useState(0);
    const [form, setForm] = useState({
      fname: '',
      lname: '',
      username: '',
      phone: '',
      email: '',
      password: '',
      confirm: '',
      isValidFname: false,
      isValidLname: false,
      isValidPhone: false,
      isValidUser: false,
      isValidEmail: false, 
      isValidPassword: false,
      passwordsMatch: false,
      attemptedSubmit: false,
      token: '',
    });



    const goNext = async () => {
      if (!form.attemptedSubmit) {
        setForm({
          ...form,
          attemptedSubmit: true,
        });
      }
      try {
        const {isValidPhone} = form;
        // const {isValidFname, isValidLname, isValidPhone} = form;
        if (isValidPhone) {
          const {phone} = form;
          const code = await sendOtpStatusCode(phone);
          if (code) {
            switch (code) {
              case 200:
                const {fname, lname} = form;
                navigation.navigate('PhoneVerification', {
                  firstName: fname,
                  lastName: lname,
                  phone,
                });
                break;
              case 409:
                Alert.alert(ERROR_PHONE_IN_USE);
                break;
              default:
                Alert.alert(ERROR_TWILIO_SERVER_ERROR);
              }
            } else {
          setForm({...form, attemptedSubmit: false});
          setTimeout(() => setForm({...form, attemptedSubmit: true}));
        }
      }
    } catch (error) {
        Alert.alert(ERROR_NEXT_PAGE);
        return {
          name: 'Navigation error',
          description: error,
        };
      }
    };

    // 0 = first name, 1 = last name, 2 = username, 3 = phone #
    const handleNameUpdate= (name: string, nameType: number) => {
      name = name.trim();
      let isValidName: boolean = nameRegex.test(name);
      switch(nameType) {
        case 0:
          console.log("First name")
          setForm({
            ...form,
            fname: name,
            isValidFname: isValidName,
          });
          console.log(isValidName)
        case 1:
          setForm({
            ...form,
            lname: name,
            isValidLname: isValidName,
          });
        case 2:
          let isvalidUserName = usernameRegex.test(name);
          setForm({
            ...form,
            username: name,
            isValidUser: isValidName,
          });
        // case 3: 
        // let isValidPhone: boolean = phoneRegex.test(name);
        // setForm({
        //   ...form,
        //   phone: name,
        //   isValidPhone,
        // });
      }
      
    };
    const handlePhoneUpdate = (phone: string) => {
      phone = phone.trim();
      let isValidPhone: boolean = phoneRegex.test(phone);
      setForm({
        ...form,
        phone,
        isValidPhone,
      });
    };
    const handleEmailUpdate = (email: string) => {
      email = email.trim();
      let isValidEmail: boolean = emailRegex.test(email);
      setForm({
        ...form,
        email,
        isValidEmail,
      });
    };
    const handlePasswordUpdate = (password: string) => {
      let isValidPassword: boolean = passwordRegex.test(password);
      let passwordsMatch: boolean = form.password === form.confirm;
      setForm({
        ...form,
        password,
        isValidPassword,
        passwordsMatch,
      });
    };

    const formSteps: {
      placeholder: string,
      valid: () => boolean,
      onChangeText: (text: string, nameType: number) => void,
    }[] = [
      {
        placeholder: 'First Name',
        valid: () => form.isValidFname,
        onChangeText: (text, _) => handleNameUpdate(text, 0),
      },
      {
        placeholder: 'Last Name',
        valid: () => form.isValidLname,
        onChangeText: (text, _) => handleNameUpdate(text, 1),
      },
      {
        placeholder: 'Phone',
        valid: () => form.isValidPhone,
        onChangeText: handlePhoneUpdate,
      },
      {
        placeholder: 'School Email',
        valid: () => form.isValidEmail,
        onChangeText: handleEmailUpdate,
      },
      {
        placeholder: 'Username',
        valid: () => form.isValidLname,
        onChangeText: (text, _) => handleNameUpdate(text, 1),
      },
      {
        placeholder: 'Password',
        valid: () => form.isValidLname,
        onChangeText: handlePasswordUpdate,
      },
      // ...
    ]
    useEffect(
      () => {
        console.log("before:  " + currentStep + " " + step.placeholder)
        if(isPhoneVerified) {
          setCurrentStep(currentStep + 1)
        }
        console.log("afgter: " + currentStep + " " + step.placeholder)
      }, [isPhoneVerified])
      const step = formSteps[currentStep]
    return (
      <Background
      style={styles.container}
      gradientType={BackgroundGradientType.Light}>
      <StatusBar barStyle="light-content" />

      {/* getting rid of registration progress in onboarding*/}
      {/* <RegistrationWizard style={styles.wizard} step="one" /> */}
      <KeyboardAvoidingView
        behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
        style={styles.container}>
                <View style={styles.footer}>
        {(currentStep != 0) &&
        <ArrowButton
          direction="backward"
          onPress={() => setCurrentStep(currentStep - 1)}
        />
    }
      </View>
        {/* <View style={{backgroundColor: 'thistle', position: 'absolute', top: 0, marginTop: '45%', height: 0}}> */}
        {(step.placeholder === "Phone" && !isPhoneVerified) ? (
         <>
         <TaggInput
              maxLength={10} // currently only support US phone numbers
              accessibilityHint="Enter your phone number."
              accessibilityLabel="Phone number input field."
              placeholder="Phone Number"
              autoCompleteType="tel"
              textContentType="telephoneNumber"
              autoCapitalize="none"
              keyboardType="number-pad"
              onChangeText={handlePhoneUpdate}
              autoFocus={true}
              blurOnSubmit={false}
              valid={form.isValidPhone}
              invalidWarning={'Please enter a valid 10 digit number.'}
              attemptedSubmit={form.attemptedSubmit}
              width={280}
              onSubmitEditing={goNext} 
              />
                <TaggSquareButton
                  onPress={goNext}
                  title={'Verify'}
                  buttonStyle={'normal'}
                  buttonColor={'white'}
                  labelColor={'blue'} />
              </>
        ) : (
      <>
      <Text style={styles.formHeader}>SIGN UP</Text>
      <View style = {{position: 'absolute', top: 50}}>
            <TaggInput
            key = {step.placeholder}
            style={styles.input}
            accessibilityHint={`Enter your ${step.placeholder.toLowerCase()}`}
            accessibilityLabel={`${step.placeholder} input field.`}
            placeholder={currentStep + " " + step.placeholder}
            autoCompleteType="name"
            textContentType="name"
            returnKeyType="next"
            onChangeText={step.onChangeText}
            onSubmitEditing={() => 
              { console.log("step bool:" + step.placeholder + " " + form.isValidFname)
                if (step.valid()) {setCurrentStep(currentStep + 1)}}}
            autoFocus= {true}
            blurOnSubmit={false}
            valid={step.valid()}
            invalidWarning={`Please enter a valid ${step.placeholder.toLowerCase()}`}
            attemptedSubmit={form.attemptedSubmit}
            width={280}
          />
        <TaggSquareButton
          onPress={() => {if (step.valid()) {setCurrentStep(currentStep + 1)}}}
          autoFocus= {true}
          title={'Next'}
          buttonStyle={'normal'}
          buttonColor={'white'}
          labelColor={'blue'}
        />
          </View>
          </>)}
          <View style = {{position: 'absolute', bottom: 150}}>
        </View>
      </KeyboardAvoidingView>
    </Background> 
    )};
// in return listen for button click, if fname valid, then change state to return the next component in the list 
// conditionally display subsequent components. 

const styles = StyleSheet.create({
    container: {
      height: SCREEN_HEIGHT,
      width: SCREEN_WIDTH,
      alignItems: 'center',
      justifyContent: 'center',
    },
    input: {
      width: '100%',
      minWidth: '60%',
      height: 40,
      fontSize: 16,
      fontWeight: '600',
      color: '#fff',
      paddingLeft: 13,
      borderBottomWidth: 1,
      borderBottomColor: '#fff'
    },
    button: {
      width: 40, 
      aspectRatio: 10,
    }, 
    formHeader: {
      color: '#fff',
      fontSize: 30,
      fontWeight: '600',
      marginBottom: '16%',
      position: 'absolute', top: 0, marginTop: '45%',
    },
    load: {
      top: '5%',
    },
    footer: {
      width: '100%',
      flexDirection: 'row',
      justifyContent: 'space-around',
      ...Platform.select({
        ios: {
          bottom: '20%',
        },
        android: {
          bottom: '10%',
        },
      }),
    },
  });
export default RevampedOnboarding;
