import React, { useEffect, useState } from "react";
import { StyleSheet, Alert, Image, TouchableOpacity } from "react-native";
import { ThemedText } from "@/components/ThemedText";
import { ThemedView } from "@/components/ThemedView";
import { getUserData } from "@/components/services/securestorage/UserData";
import { Colors } from '@/constants/Colors';
import { useColorScheme } from '@/hooks/useColorScheme';
import * as ImagePicker from 'expo-image-picker';

type UserData = {
  fullName: string;
  appleEmail: string;
  pfpURL: string;
  // Add other fields as needed
};

const Index = () => {
  const scheme = useColorScheme() ?? 'light';
  const [userData, setUserData] = useState<UserData | null>(null);

  useEffect(() => {
    const fetchUserData = async () => {
      try {
        const data = await getUserData();
        setUserData(data);
      } catch (error) {
        console.error("Error fetching user data:", error);
        Alert.alert("Error", "Failed to load user data");
      }
    };

    fetchUserData();
  }, []);

  const handleUpdateProfilePicture = async () => {
    const permissionResult = await ImagePicker.requestMediaLibraryPermissionsAsync();
    
    if (permissionResult.granted === false) {
      Alert.alert("Permission Required", "You need to grant permission to access your photos");
      return;
    }

    const result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.Images,
      allowsEditing: true,
      aspect: [1, 1],
      quality: 1,
    });

    if (!result.canceled) {
      // Here you would typically upload the image to your server
      // and update the user's profile picture URL
      console.log("Selected image:", result.assets[0].uri);
      // For now, let's just update the local state
      setUserData(prevData => prevData ? {...prevData, pfpURL: result.assets[0].uri} : null);
    }
  };

  return (
    <ThemedView style={styles.container}>
      {userData ? (
        <ThemedView style={styles.profileContainer}>
          <TouchableOpacity onPress={handleUpdateProfilePicture}>
            <Image
              source={userData.pfpURL ? { uri: userData.pfpURL } : require('@/assets/images/default-profile.png')}
              style={styles.profilePicture}
            />
          </TouchableOpacity>
          <ThemedText style={styles.name}>{userData.fullName}</ThemedText>
          <ThemedText style={styles.email}>{userData.appleEmail}</ThemedText>
        </ThemedView>
      ) : (
        <ThemedText>Loading user data...</ThemedText>
      )}
      <ThemedView style={styles.footerContainer}>
        {/* Add your relationship request button or other components here */}
      </ThemedView>
    </ThemedView>
  );
}

export default Index;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
  },
  profileContainer: {
    alignItems: 'center',
    marginTop: 20,
    marginBottom: 20,
  },
  profilePicture: {
    width: 100,
    height: 100,
    borderRadius: 50,
    marginBottom: 10,
  },
  name: {
    fontSize: 24,
    fontWeight: 'bold',
    marginBottom: 5,
  },
  email: {
    fontSize: 16,
    marginBottom: 20,
  },
  footerContainer: {
    flex: 1 / 3, 
    alignItems: 'center',
  },
});
