import React, { useState, useEffect } from 'react';
import { View, Text, Button, ScrollView, RefreshControl, ActivityIndicator } from 'react-native';
import { useTailwind } from 'tailwind-rn'
import AsyncStorage from '@react-native-async-storage/async-storage';
import Icon from 'react-native-vector-icons/FontAwesome'
import { TouchableOpacity } from 'react-native';
import { HeaderButtons, Item } from 'react-navigation-header-buttons';
import CreateSwitButton from './components/Create';
// import date
import moment from 'moment';
import { Swit } from './Home';


function HomeScreen({ navigation }) {
  const [swits, setSwits] = useState([]);
  const [refreshing, setRefreshing] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [errorMessage, setErrorMessage] = useState('');
  const [userId, setUserId] = useState('');

  async function fetchSwits() {
    setIsLoading(true)
    const token = await AsyncStorage.getItem('token');
    const apiUrl = await AsyncStorage.getItem('apiEndpoint')

    setErrorMessage('');
    try {
      setErrorMessage('');
      const response = await fetch(`${apiUrl}/api/v1/app/swit/swits/following`, {
        headers: { 'Authorization': token },
      });

      if (!response.ok) {
        const errorText = await response.text();
        setErrorMessage(errorText);
        return;
      }
      const swits = await response.json();
      setSwits(swits);
    } catch (error) {
      console.log(error);
      setErrorMessage('Something went wrong');
    }
    setIsLoading(false)
    return;
  }

  useEffect(() => {
    const unsubscribe = navigation.addListener('focus', fetchSwits);
    return unsubscribe;
  }, [navigation]);

  useEffect(() => {
    async function fetchUserId() {
      const id = await AsyncStorage.getItem('userID');
      setUserId(id);
    }
    fetchUserId();
  }, []);

  useEffect(() => {
    navigation.setOptions({
      headerRight: () => (
        <HeaderButtons HeaderButtonComponent={CreateSwitButton}>
          <Item
            title="Add"
            iconName="ios-add"
            onPress={() => {
              navigation.navigate('Swit');
            }}
          />
        </HeaderButtons>
      ),
    });
  }, [navigation]);
  

  const tailwind = useTailwind();

  if (isLoading) {
    return (
      <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
      <ActivityIndicator size="large" color="#0000ff" />
    </View>
    )
  }

  return (
    <View style={tailwind('p-4')}>
                  {errorMessage ? <Text style={tailwind('text-red-500 mb-2 text-center')}>{errorMessage}</Text> : null}
      <ScrollView
        refreshControl={
          <RefreshControl
            refreshing={refreshing}
            onRefresh={async () => {
              setRefreshing(true);
              await fetchSwits();
              setRefreshing(false);
            }}
          />
        }
      >
        {swits.map(swit => (
          <Swit swit={swit} navigation={navigation} userId={userId} setSwits={setSwits} swits={swits}/>
          ))}

      </ScrollView>
    </View>
  );
  
}

export default HomeScreen;