// src/screens/ProfileScreen.tsx
import React, { useState, useEffect } from 'react';
import { View, StyleSheet, ActivityIndicator, Alert } from 'react-native';
import { Text, Button, useTheme, Card, Title, Paragraph } from 'react-native-paper';
import { useAuth } from '../contexts/AuthContext';
import apiClient from '../api/client';

// Define an interface for the user data structure
interface UserProfile {
  username: string;
  name: string;
  uuid: string;
  role: string;
}

const ProfileScreen = () => {
  const theme = useTheme();
  const { logout } = useAuth(); // Get the logout function
  const [userProfile, setUserProfile] = useState<UserProfile | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const fetchUserProfile = async () => {
      setIsLoading(true);
      setError(null);
      try {
        const response = await apiClient.get<UserProfile>('/user/me');
        setUserProfile(response.data);
      } catch (err: any) {
        console.error("Failed to fetch user profile:", err);
        setError(err.response?.data?.detail || err.message || 'Failed to load profile.');
      } finally {
        setIsLoading(false);
      }
    };

    fetchUserProfile();
  }, []); // Empty dependency array means this runs once on mount

  const handleLogout = async () => {
    try {
      await logout();
      // Navigation to login screen will likely happen automatically
      // due to the state change in AuthProvider re-rendering the navigator
    } catch (err) {
      console.error("Logout failed:", err);
      Alert.alert("Logout Error", "Could not log out. Please try again.");
    }
  };

  const styles = StyleSheet.create({
    container: {
        flex: 1,
        padding: 16,
        backgroundColor: theme.colors.background,
        justifyContent: 'space-between', // Pushes logout button to bottom
    },
    contentContainer: {
        flex: 1, // Takes up available space
        alignItems: 'center',
        justifyContent: 'center', // Center content vertically
    },
    card: {
        width: '100%',
        maxWidth: 400, // Optional: constrain width on larger screens
        marginBottom: 20,
        backgroundColor: theme.colors.surface, // Use theme surface color
    },
    errorText: {
        fontSize: 16,
        color: theme.colors.error,
        textAlign: 'center',
        marginBottom: 20,
    },
    logoutButton: {
        marginTop: 'auto', // Pushes button to the bottom within its container
        marginBottom: 20, // Add some space at the very bottom
    },
    // Removed text style as Paper components handle theme text color
  });

  if (isLoading) {
    return (
      <View style={[styles.container, { justifyContent: 'center', alignItems: 'center' }]}>
        <ActivityIndicator size="large" color={theme.colors.primary} />
      </View>
    );
  }

  return (
    <View style={styles.container}>
        <View style={styles.contentContainer}>
            {error && <Text style={styles.errorText}>{error}</Text>}

            {userProfile ? (
                <Card style={styles.card}>
                <Card.Content>
                    <Title style={{ color: theme.colors.primary }}>User Profile</Title>
                    <Paragraph>Username: {userProfile.username}</Paragraph>
                    <Paragraph>Name: {userProfile.name}</Paragraph>
                    <Paragraph>UUID: {userProfile.uuid}</Paragraph>
                    <Paragraph>Role: {userProfile.role}</Paragraph>
                </Card.Content>
                </Card>
            ) : (
                !error && <Text>No profile data available.</Text> // Show if no error but no data
            )}
         </View>

        <Button
            mode="contained" // Use contained style for primary actions
            onPress={handleLogout}
            style={styles.logoutButton}
            icon="logout" // Add an icon
            color={theme.colors.error} // Use error color for logout/destructive action
        >
            Logout
        </Button>
    </View>
  );
};

export default ProfileScreen;
