import React, { useState } from 'react';
import { View, TextInput, Button, Image, ActivityIndicator } from 'react-native';
import { useTailwind } from 'tailwind-rn';
import AsyncStorage from '@react-native-async-storage/async-storage';
import * as ImagePicker from 'expo-image-picker';

function EditProfileScreen({ route, navigation }) {
  const { user, currentUsername, currentBio, currentPronouns, currentName } = route.params;
  const tailwind = useTailwind();
  
  const [username, setUsername] = useState(user.username);
  const [profilePicture, setProfilePicture] = useState(user.profilePicture);
  const [bio, setBio] = useState(user.bio);
  const [pronouns, setPronouns] = useState(user.pronouns);
  const [name, setName] = useState(user.name);
  const [isLoading, setIsLoading] = useState(false);
  const [errorMessage, setErrorMessage] = useState('');

  const pickImage = async () => {
    let result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.All,
      allowsEditing: true,
      aspect: [1, 1],
      quality: 1,
    });

    console.log(result);

    if (!result.cancelled) {
      setProfilePicture(result.uri);

      // Get the user's token
      const token = await AsyncStorage.getItem('token');
      const apiUrl = await AsyncStorage.getItem('apiEndpoint')


      // Create a new FormData object
      let formData = new FormData();
      // Add the image to the form data
      let uriParts = result.uri.split('.');
      let fileType = uriParts[uriParts.length - 1];
      formData.append('profilePicture', {
        uri: result.uri,
        name: `photo.${fileType}`,
        type: `image/${fileType}`,
      });

      // Upload the image
      try {
        let response = await fetch(`${apiUrl}/api/v1/app/user/profilePicture`, {
          method: 'POST',
          body: formData,
          headers: {
            'Content-Type': 'multipart/form-data',
            'Authorization': token,
          },
        });
        let responseJson = await response.json();
        console.log(responseJson);
      } catch (error) {
        console.error(error);
      }
    }
  };

  async function saveChanges() {
    setIsLoading(true);
    try {
      const token = await AsyncStorage.getItem('token');
      const apiUrl = await AsyncStorage.getItem('apiEndpoint')
      const response = await fetch(`${apiUrl}/api/v1/app/user/data/${user._id}/edit`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': token,
        },
        body: JSON.stringify({
          username,
          profilePicture,
          bio,
          pronouns,
          name,
        }),
      });
  
      if (!response.ok) {
        throw new Error(`Failed to save changes: ${response.status}`);
      }


  
      navigation.goBack();  // Go back to the profile screen
    } catch (error) {
      console.error('Error:', error);
      setErrorMessage(error.message);
    } finally {
      setIsLoading(false);
    }
  }

  return (
    <View style={tailwind('p-4')}>
      {isLoading && <ActivityIndicator size="large" color="#0000ff" />}
      {errorMessage !== '' && <Text style={tailwind('text-red-500')}>{errorMessage}</Text>}
      {profilePicture && <Image source={{ uri: profilePicture }} style={{ width: 200, height: 200 }} />}
      
      <Button title="Upload Profile Picture" onPress={pickImage} />
      <TextInput value={username} onChangeText={setUsername} placeholder={currentUsername} />
      <TextInput value={bio} onChangeText={setBio} placeholder={currentBio} />
      <TextInput value={pronouns} onChangeText={setPronouns} placeholder={currentPronouns} />
      <TextInput value={name} onChangeText={setName} placeholder={currentName} />
      
      <Button title="Save Changes" onPress={saveChanges} />
      <Button title="Cancel" onPress={() => navigation.goBack()} />
    </View>
  );
}

export default EditProfileScreen;
