import React, { useState, useEffect } from 'react';
import { Alert, StyleSheet, AppState, Image, Platform } from 'react-native';
import { supabase } from '@/lib/supabase';
import { ThemedView, ThemedText, ThemedTextButton, ThemedTextInput } from '@/components/theme';
import AppleSignIn from '@/components/auth/AppleSignIn';

// Tells Supabase Auth to continuously refresh the session automatically if
// the app is in the foreground. When this is added, you will continue to receive
// `onAuthStateChange` events with the `TOKEN_REFRESHED` or `SIGNED_OUT` event
// if the user's session is terminated. This should only be registered once.
if (Platform.OS !== 'web') {
  AppState.addEventListener('change', (state) => {
    if (state === 'active') {
      supabase.auth.startAutoRefresh();
    } else {
      supabase.auth.stopAutoRefresh();
    }
  });
}

const LoginPage = () => {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [loading, setLoading] = useState(false);
  
  // Set up auto-refreshing for web
  useEffect(() => {
    if (Platform.OS === 'web') {
      supabase.auth.startAutoRefresh();
      return () => {
        supabase.auth.stopAutoRefresh();
      };
    }
  }, []);
  
  const signInWithEmail = async () => {
    setLoading(true);
    const { error } = await supabase.auth.signInWithPassword({
      email: email,
      password: password,
    });
    if (error) Alert.alert(error.message);
    setLoading(false);
  };
  
  const signUpWithEmail = async () => {
    setLoading(true);
    const {
      data: { session },
      error,
    } = await supabase.auth.signUp({
      email: email,
      password: password,
    });
    if (error) Alert.alert(error.message);
    else if (!session) Alert.alert('Please check your inbox for email verification!');
    setLoading(false);
  };
  
  return (
    <ThemedView style={styles.container}>
      <ThemedView style={styles.titleContainer}>
        <Image source={require('@/assets/images/tech_tracker_logo.png')} style={styles.reactLogo} />
        <ThemedText type='title' style={styles.headerTitle}>
          Tech Tracker
        </ThemedText>
      </ThemedView>
      
      <ThemedView style={[styles.verticallySpaced]}>
        <ThemedTextInput
          fontSize={24}
          onChangeText={(text) => setEmail(text)}
          value={email}
          placeholder='email@address.com'
        />
      </ThemedView>
      
      <ThemedView style={styles.verticallySpaced}>
        <ThemedTextInput
          fontSize={24}
          onChangeText={(text) => setPassword(text)}
          value={password}
          secureTextEntry={true}
          placeholder='Password'
        />
      </ThemedView>
      
      <ThemedView style={[styles.verticallySpaced, styles.mt20]}>
        <ThemedTextButton
          text='Sign in'
          disabled={loading}
          onPress={() => signInWithEmail()}
          fontSize={24}
        />
      </ThemedView>
      
      <ThemedView style={styles.verticallySpaced}>
        <ThemedTextButton
          text='Sign up'
          disabled={loading}
          onPress={() => signUpWithEmail()}
          fontSize={24}
        />
      </ThemedView>
      
      {/* Apple Sign In - Only shows on iOS */}
      <ThemedView style={[styles.verticallySpaced, styles.mt20]}>
        <AppleSignIn 
          onSignInStart={() => setLoading(true)}
          onSignInComplete={() => setLoading(false)}
          onSignInError={() => setLoading(false)}
        />
      </ThemedView>
    </ThemedView>
  );
};

export default LoginPage;

const styles = StyleSheet.create({
  container: {
    padding: 12,
    height: '100%',
  },
  verticallySpaced: {
    paddingTop: 4,
    paddingBottom: 4,
    alignItems: 'center',
  },
  mt20: {
    marginTop: 20,
  },
  reactLogo: {
    height: 70,
    width: 72,
  },
  titleContainer: {
    marginTop: 60,
    marginBottom: 20,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    gap: 8,
  },
  headerTitle: {
    textAlign: 'center',
    fontSize: 48,
    lineHeight: 64,
    fontWeight: 'bold',
  },
  divider: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    marginVertical: 20,
  },
  dividerText: {
    marginHorizontal: 10,
    fontSize: 16,
    opacity: 0.7,
  },
});
