import React, { useState, useEffect } from 'react';
import { View, Text, Button, Image, ActivityIndicator, RefreshControl, TextInput } from 'react-native';
import { useTailwind } from 'tailwind-rn';
import AsyncStorage from '@react-native-async-storage/async-storage';
import * as ImagePicker from 'expo-image-picker';
import { Swit } from './Home';
import { ScrollView } from 'react-native-gesture-handler';



function ProfileScreen({ navigation }) {
  const [username, setUsername] = useState('');
  const [profilePicture, setProfilePicture] = useState(null);
  const [bio, setBio] = useState('');
  const [pronouns, setPronouns] = useState('');
  const [name, setName] = useState('');


  const tailwind = useTailwind();

  const [following, setFollowing] = useState([]);
  const [followers, setFollowers] = useState([]);
  const [isLoading, setIsLoading] = useState(false);
  const [errorMessage, setErrorMessage] = useState('');
  const [userSwits, setUserSwits] = useState([]);
  const [userId, setUserId] = useState('');
  const [refreshing, setRefreshing] = useState(false);


  async function fetchUserData() {
    setIsLoading(true);
    try {
      const userId = await AsyncStorage.getItem('userID');
      const token = await AsyncStorage.getItem('token');
      const apiUrl = await AsyncStorage.getItem('apiEndpoint')
      const response = await fetch(`${apiUrl}/api/v1/app/user/data/${userId}`, {
        headers: { 'Authorization': token },
      });
  
      if (!response.ok) {
        throw new Error(`Failed to fetch user data: ${response.status}`);
      }
  
      const user = await response.json();
      setUsername(user.username);
      setFollowing(user.following);
      setProfilePicture(user.profilePicture);
  
      const followersResponse = await fetch(`${apiUrl}/api/v1/app/user/followers/${userId}`, {
        headers: { 'Authorization': token },
      });
  
      if (!followersResponse.ok) {
        throw new Error(`Failed to fetch followers: ${followersResponse.status}`);
      }
  
      const followersData = await followersResponse.json();
      setFollowers(followersData);
      setBio(user.bio);
      setPronouns(user.pronouns);
      setName(user.name);


      const userPostedSwits = await fetch(`${apiUrl}/api/v1/app/swit/swits/user/${userId}`, {
        headers: { 'Authorization': token },
        });
        if (!userPostedSwits.ok) {
          throw new Error(`Failed to fetch swits: ${userPostedSwits.status}`);
        }
        const userPostedSwitsData = await userPostedSwits.json();
        setUserSwits(userPostedSwitsData);


    } catch (error) {
      console.error('Error:', error);
      setErrorMessage(error.message);
    } finally {
      setIsLoading(false);
    }
  }



  

  useEffect(() => {
    setUserId(AsyncStorage.getItem('userID'));
    fetchUserData();

  }, []);

  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 }} />}  
          <Text style={tailwind('text-lg')}>Username: {username}</Text>
          <Text style={tailwind('text-lg')}>Bio: {bio}</Text>
          <Text style={tailwind('text-lg')}>Pronouns: {pronouns}</Text>
          <Text style={tailwind('text-lg')}>Name: {name}</Text>
          <Button title="Edit Profile" onPress={() => navigation.navigate('EditProfile', { user: userId, currentUsername: username, currentBio: bio, currentPronouns: pronouns, currentName: name })} />
      
  
      <Text style={tailwind('text-lg')}>Following: {following.length}</Text>
      
      <Text style={tailwind('text-lg')}>Followers: {followers.length}</Text>
      
      <Button title="Settings" onPress={() => navigation.navigate('Settings')} />

      <ScrollView
        refreshControl={
          <RefreshControl
            refreshing={refreshing}
            onRefresh={async () => {
              setRefreshing(true);
              await fetchSwits();
              setRefreshing(false);
            }}
          />
        }
      >
        {userSwits.map(swit => (
          <Swit swit={swit} navigation={navigation} userId={userId} setSwits={setUserSwits} swits={userSwits}/>
        ))}

      </ScrollView>
    </View>
  );
}

export default ProfileScreen;
