import React from 'react';
import * as AppleAuthentication from 'expo-apple-authentication';
import { StyleSheet, Alert } from 'react-native';
import { ThemedView } from '@/components/ThemedView';
import { useColorScheme } from '@/hooks/useColorScheme';
import * as Notifications from 'expo-notifications';
import Constants from 'expo-constants';
import { saveUserData } from '@/components/services/securestorage/UserData';

export default function SignInScreen({ onSignIn }: { onSignIn: () => void }) {
  const scheme = useColorScheme() ?? 'light';

  const handleAppleSignIn = async () => {
    try {
      const credential = await AppleAuthentication.signInAsync({
        requestedScopes: [
          AppleAuthentication.AppleAuthenticationScope.FULL_NAME,
          AppleAuthentication.AppleAuthenticationScope.EMAIL,
        ],
      });

      const projectId = Constants.expoConfig?.extra?.eas?.projectId;
      if (!projectId) {
        throw new Error('Project ID not found');
      }

      const pushToken = await Notifications.getExpoPushTokenAsync({
        projectId: projectId
      });

      console.log(credential.user, credential.email, credential.fullName?.givenName, credential.fullName?.familyName, pushToken);

      const checkUserResponse = await
        fetch(`${process.env.EXPO_PUBLIC_API_URL}/users/getUserByAppleId?appleId=${credential.user}`, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
          'x-api-key': process.env.EXPO_PUBLIC_API_KEY ?? '',
        },
      });

      if (checkUserResponse.status === 404) {
        if (!credential.user || !credential.email || !credential.fullName?.givenName
          || !credential.fullName?.familyName) {
          Alert.alert('Sign In Error', 'Unable to create account. Please try again or contact support.');
          throw new Error('Incomplete user data for new account creation');
        }

        const response = await fetch(`${process.env.EXPO_PUBLIC_API_URL}/users/createUser`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'x-api-key': process.env.EXPO_PUBLIC_API_KEY ?? '',
          },
          body: JSON.stringify({
            appleId: credential.user,
            appleEmail: credential.email,
            fullName: `${credential.fullName?.givenName} ${credential.fullName?.familyName}`,
            pushToken: pushToken.data,
          }),
        });
        if (!response.ok) {
          const errorBody = await response.text();
          console.error('API Error:', response.status, errorBody);
          throw new Error(`Failed to create user: ${response.status} ${errorBody}`);
        }
        const userData = await response.json();
        await saveUserData(userData);
      } else if (checkUserResponse.ok) {
        const userData = await checkUserResponse.json();
        console.log('Existing user found:', JSON.stringify(userData));
        // check if push token should be updated
        if (userData.pushToken !== pushToken.data) {
          const updatePushTokenResponse =
            await fetch(`${process.env.EXPO_PUBLIC_API_URL}/users/updatePushTokenByAppleId`, {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
              'x-api-key': process.env.EXPO_PUBLIC_API_KEY ?? '',
            },
            body: JSON.stringify({
              appleId: credential.user,
              pushToken: pushToken.data,
            }),
          });
          if (!updatePushTokenResponse.ok) {
            throw new Error('Failed to update push token');
          }
        } else {
          console.log('Push token is up to date');
        }
        userData.pushToken = pushToken.data;
        await saveUserData(userData);
      }

      onSignIn();
    } catch (error) {
      console.error('Error signing in:', error);
      if (error.code === 'ERR_REQUEST_CANCELLED') {
        Alert.alert('Sign In Cancelled', 'It seems like you canceled the sign in process.');
      } else {
        Alert.alert('Sign In Error', 'An error occurred while signing in. Please try again or contact support.');
      }
    }
  };

  return (
    <ThemedView style={styles.container}>
      <AppleAuthentication.AppleAuthenticationButton
        buttonType={AppleAuthentication.AppleAuthenticationButtonType.SIGN_IN}
        buttonStyle={(scheme === 'light') ?
          AppleAuthentication.AppleAuthenticationButtonStyle.BLACK :
          AppleAuthentication.AppleAuthenticationButtonStyle.WHITE
        }
        cornerRadius={5}
        style={styles.button}
        onPress={handleAppleSignIn}
      />
    </ThemedView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
  button: {
    width: 200,
    height: 44,
  },
});
