// src/screens/RegisterScreen.tsx
import React, { useState } from 'react';
import { View, StyleSheet, KeyboardAvoidingView, Platform, Alert } from 'react-native';
import { TextInput, Button, Text, useTheme, HelperText, ActivityIndicator, Avatar } from 'react-native-paper';
import { useAuth } from '../contexts/AuthContext';
import { NativeStackScreenProps } from '@react-navigation/native-stack';
import { AuthStackParamList } from '../types/navigation'; // Import from the new types file

type RegisterScreenProps = NativeStackScreenProps<AuthStackParamList, 'Register'>;

const RegisterScreen: React.FC<RegisterScreenProps> = ({ navigation }) => {
  const theme = useTheme();
  const { register } = useAuth();
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [name, setName] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const handleRegister = async () => {
    console.log("[RegisterScreen] handleRegister: Button pressed.");
    if (!username || !password || !name || !confirmPassword) {
      setError('Please fill in all fields.');
      return;
    }
    if (password !== confirmPassword) {
      setError('Passwords do not match.');
      return;
    }
    setError(null);
    setIsLoading(true);
    try {
      console.log("[RegisterScreen] handleRegister: Calling context register function...");
      await register(username, password, name);
      console.log("[RegisterScreen] handleRegister: Registration successful (from context perspective).");
      // Show success message and navigate back to Login
      navigation.navigate('Login');
    } catch (err: any) {
      console.log("[RegisterScreen] handleRegister: Caught error from context register.");
      const errorMessage = err.response?.data?.detail ||
                           err.response?.data?.message ||
                           err.message ||
                           'Registration failed. Please try again.';
      setError(errorMessage);
    } finally {
      setIsLoading(false);
      console.log("[RegisterScreen] handleRegister: Set loading to false.");
    }
  };

  const styles = StyleSheet.create({
    container: {
      flex: 1,
      justifyContent: 'center',
      padding: 20,
      backgroundColor: theme.colors.background,
    },
    logoContainer: {
        alignItems: 'center',
        marginBottom: 30, // Slightly less margin than login
    },
    title: {
      fontSize: 24,
      fontWeight: 'bold',
      textAlign: 'center',
      marginBottom: 20,
      color: theme.colors.primary,
    },
    input: {
      marginBottom: 12, // Slightly less margin
    },
    button: {
      marginTop: 10,
      paddingVertical: 8,
    },
    loginButton: {
        marginTop: 15,
    },
    errorText: {
      textAlign: 'center',
      marginBottom: 10,
    },
    loadingContainer: {
        marginTop: 20,
    }
  });

  return (
    <KeyboardAvoidingView
      behavior={Platform.OS === "ios" ? "padding" : "height"}
      style={styles.container}
    >
        <View style={styles.logoContainer}>
            <Avatar.Image
                size={90} // Slightly smaller logo
                source={require('../assets/MAIA_ICON.png')}
            />
        </View>
      <Text style={styles.title}>Create Account</Text>
      <TextInput
        label="Name"
        value={name}
        onChangeText={setName}
        mode="outlined"
        style={styles.input}
        autoCapitalize="words"
        disabled={isLoading}
      />
      <TextInput
        label="Username"
        value={username}
        onChangeText={setUsername}
        mode="outlined"
        style={styles.input}
        autoCapitalize="none"
        disabled={isLoading}
      />
      <TextInput
        label="Password"
        value={password}
        onChangeText={setPassword}
        mode="outlined"
        style={styles.input}
        secureTextEntry
        disabled={isLoading}
      />
      <TextInput
        label="Confirm Password"
        value={confirmPassword}
        onChangeText={setConfirmPassword}
        mode="outlined"
        style={styles.input}
        secureTextEntry
        disabled={isLoading}
      />

       <HelperText type="error" visible={!!error} style={styles.errorText}>
         {error}
       </HelperText>

      {isLoading ? (
          <ActivityIndicator animating={true} color={theme.colors.primary} style={styles.loadingContainer}/>
      ) : (
          <Button
            mode="contained"
            onPress={handleRegister}
            style={styles.button}
            disabled={isLoading}
            icon="account-plus"
         >
            Register
          </Button>
      )}

      {/* Button to go back to Login */} 
      <Button
        mode="text" // Use text button for secondary action
        onPress={() => navigation.navigate('Login')}
        style={styles.loginButton}
        disabled={isLoading}
        icon="arrow-left"
      >
        Back to Login
      </Button>

    </KeyboardAvoidingView>
  );
};

export default RegisterScreen;
