import React, { useState, useEffect } from 'react';
import { View, Text, TextInput, TouchableOpacity, ActivityIndicator, Image, Switch, ScrollView, KeyboardAvoidingView, Platform, Alert, useColorScheme } from 'react-native';
import { useNavigation } from '@react-navigation/native';
import { NativeStackNavigationProp } from '@react-navigation/native-stack';
import { authService } from '../services/api';
import { getThemeStyles, commonStyles } from '../theme/styles';
import { COLORS } from '../theme/colors';
import SocialButtons from '../components/SocialButtons';
import * as AppleAuthentication from 'expo-apple-authentication';
import * as Google from 'expo-auth-session/providers/google';
import * as Facebook from 'expo-auth-session/providers/facebook';
import * as WebBrowser from 'expo-web-browser';
import { GOOGLE_CONFIG, FACEBOOK_CONFIG } from '../config/social';
import { useAuthStore } from '../store/useAuthStore';
import { RootStackParamList } from '../navigation/AppNavigator';

WebBrowser.maybeCompleteAuthSession();

type AuthScreenNavigationProp = NativeStackNavigationProp<RootStackParamList, 'Auth'>;

export default function AuthScreen() {
  const navigation = useNavigation<AuthScreenNavigationProp>();
  const login = useAuthStore((state) => state.login);
  
  const colorScheme = useColorScheme();
  const isDark = colorScheme === 'dark';
  const themeStyles = getThemeStyles(isDark);
  const brandColor = isDark ? COLORS.DARK.brand : COLORS.LIGHT.brand;

  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [username, setUsername] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [tosAccepted, setTosAccepted] = useState(false);
  const [isRegistering, setIsRegistering] = useState(false);
  const [loading, setLoading] = useState(false);

  const [googleRequest, googleResponse, promptGoogleAsync] = Google.useAuthRequest(GOOGLE_CONFIG);
  const [fbRequest, fbResponse, promptFacebookAsync] = Facebook.useAuthRequest(FACEBOOK_CONFIG);

  useEffect(() => {
    if (googleResponse?.type === 'success') {
      const { authentication } = googleResponse;
      if (authentication?.accessToken) {
        handleSocialLogin('google', authentication.accessToken);
      }
    }
  }, [googleResponse]);

  useEffect(() => {
    if (fbResponse?.type === 'success') {
      const { authentication } = fbResponse;
      if (authentication?.accessToken) {
        handleSocialLogin('facebook', authentication.accessToken);
      }
    }
  }, [fbResponse]);

  const handleLogin = async () => {
    if (!email || !password) {
      Alert.alert('Error', 'Please fill in all fields');
      return;
    }

    setLoading(true);
    try {
      const data = await authService.login(email, password);
      
      if (data.token) { 
        login(data);
      } else {
        Alert.alert('Login Failed', data.message || 'Invalid credentials');
      }
    } catch (error) {
      console.error(error);
      Alert.alert('Network Error', 'Could not connect to server.');
    } finally {
      setLoading(false);
    }
  };

  const handleRegister = async () => {
    if (!email || !username || !password || !confirmPassword) {
      Alert.alert('Error', 'Please fill in all fields');
      return;
    }

    if (password !== confirmPassword) {
      Alert.alert('Error', 'Passwords do not match');
      return;
    }

    if (!tosAccepted) {
      Alert.alert('Error', 'You must accept the Terms of Service');
      return;
    }

    setLoading(true);
    try {
      const { ok, data } = await authService.register({
        email,
        username,
        password,
        password_confirmation: confirmPassword,
        tos: true,
      });

      if (ok) {
        Alert.alert('Success', 'Account created! Please log in.');
        setIsRegistering(false);
      } else {
        const errorMessage = data.message || 'Registration failed';
        const validationErrors = data.errors ? '\n' + Object.values(data.errors).flat().join('\n') : '';
        Alert.alert('Registration Failed', errorMessage + validationErrors);
      }
    } catch (error) {
      console.error(error);
      Alert.alert('Network Error', 'Could not connect to server.');
    } finally {
      setLoading(false);
    }
  };

  const handleSocialLogin = async (provider: string, token: string) => {
    setLoading(true);
    try {
      const data = await authService.socialLogin(provider, token);
      if (data.token) {
        login(data);
      } else {
        Alert.alert('Social Login Failed', data.message || 'Could not verify token');
      }
    } catch (error) {
      Alert.alert('Error', 'Failed to connect to server');
    } finally {
      setLoading(false);
    }
  };

  const onAppleButtonPress = async () => {
    try {
      const credential = await AppleAuthentication.signInAsync({
        requestedScopes: [
          AppleAuthentication.AppleAuthenticationScope.FULL_NAME,
          AppleAuthentication.AppleAuthenticationScope.EMAIL,
        ],
      });
      if (credential.identityToken) {
        handleSocialLogin('apple', credential.identityToken);
      }
    } catch (e: any) {
      if (e.code === 'ERR_CANCELED') {
        // User canceled
      } else {
        Alert.alert('Error', 'Apple Sign In failed');
      }
    }
  };

  const toggleMode = () => {
    setIsRegistering(!isRegistering);
    setEmail('');
    setPassword('');
    setUsername('');
    setConfirmPassword('');
    setTosAccepted(false);
  };

  return (
    <KeyboardAvoidingView 
      behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
      style={themeStyles.container}
    >
      <ScrollView contentContainerStyle={commonStyles.scrollContent}>
        <View style={commonStyles.logoContainer}>
          <Image 
            source={
              isDark
                ? require('../../assets/icons/ios-dark.png') // Light logo on dark background
                : require('../../assets/icons/ios-light.png')  // Dark logo on light background
            }
            style={commonStyles.logo}
            resizeMode="contain"
          />
        </View>
        <Text style={themeStyles.headerTitle}>CasaDoc</Text>
        <Text style={[commonStyles.subtitle, themeStyles.subtitle]}>
          {isRegistering ? 'Create a new account' : 'Sign in to your account'}
        </Text>
        
        <View style={[commonStyles.form, themeStyles.card]}>
          <Text style={[commonStyles.label, themeStyles.subtitle]}>Email{isRegistering ? '' : ' or Username'}</Text>
          <TextInput
            style={[themeStyles.input]}
            placeholder={isRegistering ? "name@example.com" : "Enter email or username"}
            placeholderTextColor={isDark ? '#a0aec0' : '#a0aec0'}
            value={email}
            onChangeText={setEmail}
            autoCapitalize="none"
            keyboardType={isRegistering ? "email-address" : "default"}
            autoCorrect={false}
          />

          {isRegistering && (
            <>
              <Text style={[commonStyles.label, themeStyles.subtitle]}>Username</Text>
              <TextInput
                style={[themeStyles.input]}
                placeholder="Choose a username"
                placeholderTextColor={isDark ? '#a0aec0' : '#a0aec0'}
                value={username}
                onChangeText={setUsername}
                autoCapitalize="none"
                autoCorrect={false}
              />
            </>
          )}

          <Text style={[commonStyles.label, themeStyles.subtitle]}>Password</Text>
          <TextInput
            style={[themeStyles.input]}
            placeholder="Enter your password"
            placeholderTextColor={isDark ? '#a0aec0' : '#a0aec0'}
            value={password}
            onChangeText={setPassword}
            secureTextEntry
          />

          {isRegistering && (
            <>
              <Text style={[commonStyles.label, themeStyles.subtitle]}>Confirm Password</Text>
              <TextInput
                style={[themeStyles.input]}
                placeholder="Confirm your password"
                placeholderTextColor={isDark ? '#a0aec0' : '#a0aec0'}
                value={confirmPassword}
                onChangeText={setConfirmPassword}
                secureTextEntry
              />
              
              <View style={commonStyles.tosContainer}>
                <Switch
                  value={tosAccepted}
                  onValueChange={setTosAccepted}
                  trackColor={{ false: "#767577", true: brandColor }}
                  thumbColor={tosAccepted ? "#fff" : "#f4f3f4"}
                />
                <Text style={[commonStyles.tosText, themeStyles.subtitle]}>I accept the Terms of Service</Text>
              </View>
            </>
          )}

          <TouchableOpacity 
            style={[themeStyles.button, loading && commonStyles.buttonDisabled]} 
            onPress={isRegistering ? handleRegister : handleLogin}
            disabled={loading}
          >
            {loading ? (
              <ActivityIndicator color="white" />
            ) : (
              <Text style={themeStyles.buttonText}>{isRegistering ? 'Sign Up' : 'Sign In'}</Text>
            )}
          </TouchableOpacity>

          {!isRegistering && (
            <TouchableOpacity onPress={() => navigation.navigate('ForgotPassword')} style={{ alignSelf: 'flex-end', marginTop: 10 }}>
              <Text style={themeStyles.linkText}>Forgot Password?</Text>
            </TouchableOpacity>
          )}

          <SocialButtons 
            onGooglePress={() => {
              if (googleRequest) {
                promptGoogleAsync();
              } else {
                Alert.alert('Configuration Error', 'Google Auth Request is not ready. Check Client IDs.');
              }
            }}
            onFacebookPress={() => {
              if (fbRequest) {
                promptFacebookAsync();
              } else {
                Alert.alert('Configuration Error', 'Facebook Auth Request is not ready. Check App ID.');
              }
            }}
            onApplePress={onAppleButtonPress}
          />

          <TouchableOpacity onPress={toggleMode} style={{ marginTop: 20, alignItems: 'center' }}>
            <Text style={themeStyles.linkText}>
              {isRegistering 
                ? 'Already have an account? Sign In' 
                : 'Don\'t have an account? Sign Up'}
            </Text>
          </TouchableOpacity>
        </View>
      </ScrollView>
    </KeyboardAvoidingView>
  );
}
