import {MyScreenContainer} from '@components/MyScreenContainer';
import {SlideFromLeftView} from '@helper/animations';
import {RootScreenNavigationProp} from '@navigation/navigation';
import {useNavigation} from '@react-navigation/native';
import {
  createNativeStackNavigator,
  NativeStackNavigationOptions,
} from '@react-navigation/native-stack';
import {Image, StyleSheet, Text, TextInput, View} from 'react-native';

import GoogleLogo from '@assets/google-logo.png';
import AppleLogo from '@assets/apple-logo.png';
import Logo from '@assets/logo.png';

import {MyDividerWithText} from '@components/MyDivider';
import {MyButton, MyIconButton} from '@components/MyButton';
import {MyClickableText} from '@components/MyClickableText';
import {OpenURL} from '@helper/linking';
import {Constants} from '@utils/utils';
import {MyIconInput} from '@components/MyInput';
import {useRef, useState} from 'react';
import {KeyboardAvoidingView} from 'react-native';

export type RegistrationStackNavigatorParamList = {
  SignUpPreview: undefined;
  SignUpStepUsername: undefined;
  SignUpStepPhoneNumber: undefined;
  SignUpStepVerifyPhoneNumber: undefined;
  SignUpStepPassword: undefined;
  SignUpStepAccountName: undefined;
  LoginPreview: undefined;
  Login: undefined;
};

const RegistrationStack =
  createNativeStackNavigator<RegistrationStackNavigatorParamList>();

export function RegistrationScreenAnim(props: any) {
  return (
    <SlideFromLeftView>
      <RegistrationScreen {...props} />
    </SlideFromLeftView>
  );
}

const headerStyle: NativeStackNavigationOptions = {
  headerShown: true,
  headerStyle: {backgroundColor: '#212137'},
  headerTitleAlign: 'center',
  headerTitle: '',
};

export function RegistrationScreen() {
  return (
    <RegistrationStack.Navigator screenOptions={{headerShown: false}}>
      <RegistrationStack.Screen
        name="SignUpPreview"
        component={SignUpPreview}
      />
      <RegistrationStack.Screen name="LoginPreview" component={LoginPreview} />
      <RegistrationStack.Screen
        name="Login"
        component={Login}
        options={{
          headerShown: true,
          headerStyle: {backgroundColor: '#212137'},
          headerTitleAlign: 'center',
        }}
      />
      <RegistrationStack.Screen
        name="SignUpStepUsername"
        component={SignUpStepUsername}
        options={{...headerStyle}}
      />
      <RegistrationStack.Screen
        name="SignUpStepPhoneNumber"
        component={SignUpStepPhoneNumber}
        options={{...headerStyle}}
      />
      <RegistrationStack.Screen
        name="SignUpStepVerifyPhoneNumber"
        component={SignUpStepVerifyPhoneNumber}
        options={{...headerStyle}}
      />
      <RegistrationStack.Screen
        name="SignUpStepPassword"
        component={SignUpStepPassword}
        options={{...headerStyle}}
      />
      <RegistrationStack.Screen
        name="SignUpStepAccountName"
        component={SignUpStepAccountName}
        options={{...headerStyle}}
      />
    </RegistrationStack.Navigator>
  );
}

function SignUpPreview() {
  return <RegistrationPreview type="signup" />;
}

function LoginPreview() {
  return <RegistrationPreview type="login" />;
}

function ThirdAuthButtons() {
  return (
    <>
      <MyIconButton
        image={GoogleLogo}
        imageStyle={{left: 2, height: 35, width: 35}}
        text="Continue with Google"
      />

      <MyIconButton
        image={AppleLogo}
        imageStyle={{height: 40, width: 40}}
        text="Continue with Apple"
      />
    </>
  );
}

function RegistrationPreview({type}: {type: 'login' | 'signup'}) {
  const navigation = useNavigation<RootScreenNavigationProp>();

  return (
    <MyScreenContainer
      style={{
        flex: 1,
        flexDirection: 'column',
        backgroundColor: '#212137',
      }}>
      <View style={{flex: 1, marginTop: 10, alignItems: 'center'}}>
        <Image source={Logo} style={{height: 60, width: 60}} />
      </View>

      <View style={{flex: 2, justifyContent: 'center'}}>
        <Text
          style={{
            fontSize: 24,
            fontWeight: 'bold',
            textAlign: 'center',
            color: '#fff',
            padding: 20,
          }}>
          {type === 'login'
            ? 'Time to get to know the next party'
            : 'Find the next party near you'}
        </Text>
      </View>

      <View
        style={{
          gap: 10,
          flex: 3,
          justifyContent: 'flex-end',
          marginBottom: 20,
        }}>
        <ThirdAuthButtons />

        <MyDividerWithText text="or" />

        <MyButton
          type="secondary"
          text={type === 'login' ? 'Login' : 'Create account'}
          style={{marginBottom: 20}}
          onPress={() => {
            navigation.navigate(
              'Registration',
              type === 'login'
                ? {screen: 'Login'}
                : {screen: 'SignUpStepUsername'},
            );
          }}
        />

        {type === 'login' && (
          <View style={{flexDirection: 'row', flexWrap: 'wrap'}}>
            <Text>By signing up, you agree to our </Text>
            <MyClickableText
              text="Terms"
              textStyle={{color: '#6030da'}}
              onPress={() => OpenURL(Constants.REGISTRATION.TERMS_URL)}
            />
            <Text>, </Text>
            <MyClickableText
              text="Privacy Policy"
              textStyle={{color: '#6030da'}}
              onPress={() => OpenURL(Constants.REGISTRATION.PRIVACY_POLICY_URL)}
            />
            <Text> and </Text>
            <MyClickableText
              text="Cookie Use"
              textStyle={{color: '#6030da'}}
              onPress={() => OpenURL(Constants.REGISTRATION.COOKIE_USE_URL)}
            />
            <Text>.</Text>
          </View>
        )}

        <View style={{flexDirection: 'row'}}>
          {type === 'login' ? (
            <Text>Don't have an account?</Text>
          ) : (
            <Text>Have already an account?</Text>
          )}

          <MyClickableText
            text={type === 'login' ? 'Sign up' : 'Login'}
            textStyle={{left: 2, color: '#931278', fontWeight: 'bold'}}
            onPress={() => {
              navigation.navigate(
                'Registration',
                type === 'login'
                  ? {screen: 'SignUpPreview'}
                  : {screen: 'LoginPreview'},
              );
            }}
          />
        </View>
      </View>
    </MyScreenContainer>
  );
}

function ContentContainer({children}: {children: React.ReactNode}) {
  return (
    <>
      <View style={{flex: 1}} />
      <View style={{flex: 8}}>{children}</View>
    </>
  );
}

function Title({text}: {text: string}) {
  return (
    <Text
      style={{
        fontSize: 24,
        fontWeight: 'bold',
        textAlign: 'center',
        color: '#fff',
        padding: 20,
      }}>
      {text}
    </Text>
  );
}

function Login() {
  const navigation = useNavigation<RootScreenNavigationProp>();

  return (
    <MyScreenContainer
      style={{
        flex: 1,
        flexDirection: 'column',
        backgroundColor: '#212137',
      }}>
      <ContentContainer>
        <Title text="Welcome back!" />

        <View style={{gap: 12}}>
          <MyIconInput text="PHONE NUMBER OR ACCOUNT NAME" iconName="person" />
          <MyIconInput text="PASSWORD" iconName="lock" secureTextEntry />

          <MyButton
            type="secondary"
            text={'Login'}
            style={{marginBottom: 20}}
            onPress={() => {
              navigation.navigate('Home');
            }}
          />
        </View>
      </ContentContainer>
    </MyScreenContainer>
  );
}

function SignUpStepUsername() {
  const navigation = useNavigation<RootScreenNavigationProp>();

  return (
    <MyScreenContainer
      style={{
        flex: 1,
        flexDirection: 'column',
        backgroundColor: '#212137',
      }}>
      <ContentContainer>
        <Title text="Let's get started, what's your name?" />
        <Text>The name will be displayed on your profil overview</Text>

        <View style={{gap: 12, marginTop: 20}}>
          <MyIconInput text="Username" iconName="person" />

          <MyButton
            type="secondary"
            text={'Next'}
            style={{marginBottom: 20}}
            onPress={() => {
              navigation.navigate('Registration', {
                screen: 'SignUpStepPhoneNumber',
              });
            }}
          />
        </View>
      </ContentContainer>
    </MyScreenContainer>
  );
}

function SignUpStepPhoneNumber() {
  const navigation = useNavigation<RootScreenNavigationProp>();

  return (
    <MyScreenContainer
      style={{
        flex: 1,
        flexDirection: 'column',
        backgroundColor: '#212137',
      }}>
      <ContentContainer>
        <Title text="Create your account using your phone number" />

        <View style={{gap: 12, marginTop: 20}}>
          <MyIconInput
            text="Phone"
            iconName="phone-iphone"
            keyboardType="phone-pad"
          />

          <MyButton
            type="secondary"
            text={'Next'}
            style={{marginBottom: 20}}
            onPress={() => {
              navigation.navigate('Registration', {
                screen: 'SignUpStepVerifyPhoneNumber',
              });
            }}
          />
        </View>
      </ContentContainer>
    </MyScreenContainer>
  );
}

interface ConfirmationCodeInputProps {
  // Zusätzliche Props für das ConfirmationCodeInput-Komponente hier hinzufügen
}

const ConfirmationCodeInput: React.FC<ConfirmationCodeInputProps> = () => {
  const [confirmationCode, setConfirmationCode] = useState([
    '',
    '',
    '',
    '',
    '',
    '',
  ]);
  const inputRefs = useRef<TextInput[]>([]);

  const focusInput = (index: number) => {
    if (inputRefs.current[index]) {
      inputRefs.current[index].focus();
    }
  };

  const handleTextChange = (text: string, index: number) => {
    const newConfirmationCode = [...confirmationCode];
    newConfirmationCode[index] = text;

    // Fokus zum nächsten Input verschieben, wenn der aktuelle Input nicht leer ist
    if (text !== '' && index < confirmationCode.length - 1) {
      focusInput(index + 1);
    }

    setConfirmationCode(newConfirmationCode);
  };

  return (
    <View style={styles.container}>
      {confirmationCode.map((digit, index) => (
        <TextInput
          key={index}
          ref={ref => (inputRefs.current[index] = ref!)}
          style={styles.input}
          keyboardType="number-pad"
          maxLength={1}
          onChangeText={text => handleTextChange(text, index)}
          value={digit}
        />
      ))}
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flexDirection: 'row',
    justifyContent: 'center',
  },
  input: {
    height: 40,
    width: 40,
    borderColor: 'gray',
    borderWidth: 1,
    textAlign: 'center',
    margin: 5,
    borderRadius: 5,
  },
});

function SignUpStepVerifyPhoneNumber() {
  const navigation = useNavigation<RootScreenNavigationProp>();

  return (
    <MyScreenContainer
      style={{
        flex: 1,
        flexDirection: 'column',
        backgroundColor: '#212137',
      }}>
      <ContentContainer>
        <Title text="We sent you a code" />
        <Text>Enter it below to verify +49 15** ******43 </Text>

        <KeyboardAvoidingView style={{gap: 12, marginTop: 20}}>
          <ConfirmationCodeInput />

          <MyButton
            type="secondary"
            text={'Next'}
            style={{marginBottom: 2}}
            onPress={() => {
              navigation.navigate('Registration', {
                screen: 'SignUpStepPassword',
              });
            }}
          />
          <View style={{alignItems: 'center'}}>
            <MyClickableText text="Resend code" />
          </View>
        </KeyboardAvoidingView>
      </ContentContainer>
    </MyScreenContainer>
  );
}

function SignUpStepPassword() {
  const navigation = useNavigation<RootScreenNavigationProp>();

  return (
    <MyScreenContainer
      style={{
        flex: 1,
        flexDirection: 'column',
        backgroundColor: '#212137',
      }}>
      <ContentContainer>
        <Title text="You'll need a password" />
        <Text>Make sure it's 8 characters or more</Text>

        <View style={{gap: 12, marginTop: 20}}>
          <MyIconInput text="PASSWORD" iconName="lock" secureTextEntry />

          <MyButton
            type="secondary"
            text={'Next'}
            style={{marginBottom: 2}}
            onPress={() => {
              navigation.navigate('Registration', {
                screen: 'SignUpStepAccountName',
              });
            }}
          />
        </View>
      </ContentContainer>
    </MyScreenContainer>
  );
}

function SignUpStepAccountName() {
  const navigation = useNavigation<RootScreenNavigationProp>();

  return (
    <MyScreenContainer
      style={{
        flex: 1,
        flexDirection: 'column',
        backgroundColor: '#212137',
      }}>
      <ContentContainer>
        <Title text="Next, create your account name" />
        <Text>
          Your account name is unique and is used for friends to find you.
        </Text>

        <View style={{gap: 12, marginTop: 20}}>
          <MyIconInput text="ACCOUNT NAME" iconName="person" />

          <MyButton
            type="primary"
            text={'Get Started'}
            style={{marginBottom: 2}}
            onPress={() => {
              navigation.navigate('Home');
            }}
          />
        </View>
      </ContentContainer>
    </MyScreenContainer>
  );
}
