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, updateUserData } from "@/components/services/securestorage/UserData";
import { manipulateAsync, SaveFormat } from 'expo-image-manipulator';
import * as ImagePicker from 'expo-image-picker';
import * as FileSystem from 'expo-file-system';
import type { User } from '@/components/Types';

type UserInfoProps = {
  onProfilePictureUpdate: (url: string) => void;
};

const UserInfo: React.FC<UserInfoProps> = ({ onProfilePictureUpdate }) => {
  const [userData, setUserData] = useState<User | null>(null);

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

    fetchUserData();
  }, [onProfilePictureUpdate]);

  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 && result.assets[0].uri) {
      try {
        // Manipulate the image
        const manipResult = await manipulateAsync(
          result.assets[0].uri,
          [
            { resize: { width: 300, height: 300 } },
            // You can add more manipulations here if needed
          ],
          { compress: 0.7, format: SaveFormat.JPEG }
        );

        const apiUrl = `${process.env.EXPO_PUBLIC_API_URL}/users/updatePfp`;
        console.log("Sending request to:", apiUrl);

        const response = await FileSystem.uploadAsync(apiUrl, manipResult.uri, {
          fieldName: 'file',
          httpMethod: 'POST',
          uploadType: FileSystem.FileSystemUploadType.MULTIPART,
          parameters: { appleId: userData?.appleId || '' },
          headers: {
            'x-api-key': process.env.EXPO_PUBLIC_API_KEY ?? '',
          },
        });

        console.log('Response status:', response.status);
        console.log('Response headers:', JSON.stringify(response.headers, null, 2));
        console.log('Response body:', response.body);

        if (response.status !== 200) {
          throw new Error(`Server responded with status ${response.status}: ${response.body}`);
        }

        const responseData = JSON.parse(response.body);
        const newPfpURL = responseData.pfpURL;

        // Update local state
        setUserData(prevData => prevData ? {...prevData, pfpURL: newPfpURL} as User : null);

        // Update SecureStorage
        await updateUserData({ pfpURL: newPfpURL });
        onProfilePictureUpdate(newPfpURL);

      } catch (error) {
        console.error("Error updating profile picture:", error);
        console.error("Error details:", error.message);
        Alert.alert("Error", `Failed to update profile picture: ${error.message}`);
      }
    }
  };

  return (
    <ThemedView style={styles.container}>
      {userData ? (
        <ThemedView style={styles.profileContainer}>
          <TouchableOpacity onPress={handleUpdateProfilePicture}>
            <Image
              source={userData.pfpURL ? { uri: `${process.env.EXPO_PUBLIC_URL}${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>
  );
}

export default UserInfo;

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,
  },
});
