import { ActivityIndicator, FlatList, StyleSheet, Text, View } from 'react-native'
import { collection, query, where, getDocs, getFirestore } from "firebase/firestore";
import React, { useEffect, useState } from 'react'
import { useUser } from '@clerk/clerk-expo';
import { app } from '../misc/FirebaseConfig';
import ItemList from './googleList/ItemList';

const SaveScreen = () => {
  const {user} = useUser();
  const [saveList, setSaveList] = useState([]);
  const [isLoading, setIsLoading] = useState(false);

  db = getFirestore(app);

  useEffect(() => {
    user && getSaveList();
  }, [user])

  const getSaveList = async() => {
    setIsLoading(true);
    setSaveList([])
    const q = query(collection(db, "ev-save"), where("email", "==", user?.primaryEmailAddress?.emailAddress));

    const querySnapshot = await getDocs(q);
    querySnapshot.forEach((doc) => {
      // doc.data() is never undefined for query doc snapshots
      console.log(doc.id, " => ", doc.data());
      setSaveList(saveList => [...saveList, doc.data()]);
      setIsLoading(false);
    });
  }

  return (
    <View style={{flex: 1, backgroundColor: 'white'}}>
      {!saveList? 
        <View style={{flexDirection: 'column', alignItems: 'center', justifyContent: 'center', height: '100%'}}>
          <ActivityIndicator size={'large'} color={'#379777'}/>
          <Text style={{marginTop: 10}}>Loading</Text>
          
        </View> : null
      }
      <FlatList 
        onRefresh={() => getSaveList()}
        refreshing={isLoading}
        data={saveList}
        renderItem={({item, index}) => (
          <View key={index} style={{marginVertical: 5, marginHorizontal: 5, borderColor: 'gray', borderWidth: 1}}>
            <ItemList place={item.place} isSave={true} markedSave={() => getSaveList()}/>
          </View>
        )}
      />
    </View>
  )
}

export default SaveScreen

const styles = StyleSheet.create({})